<?php

namespace App\Http\Middleware;

use App\Installer\Services\InstallationManager;
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

/**
 * Verify Installer Integrity Middleware
 * Checks if installer code has been tampered with
 * If tampered, breaks admin and frontend functionality
 */
class VerifyInstallerIntegrity
{
    public function __construct(
        private InstallationManager $installationManager
    ) {}

    /**
     * Handle an incoming request.
     *
     * @param  \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response)  $next
     */
    public function handle(Request $request, Closure $next): Response
    {
        // Skip integrity check for installer routes
        if ($request->is('install*')) {
            return $next($request);
        }

        // Only check if application is installed
        if (! $this->installationManager->isInstalled()) {
            return $next($request);
        }

        // Local / testing: hash breaks whenever app/Installer or APP_KEY changes — do not lock dev out
        if (app()->isLocal() || app()->environment('testing')) {
            return $next($request);
        }

        if (config('installer.skip_integrity_check', false)) {
            return $next($request);
        }

        // Verify installer integrity
        if (! $this->installationManager->verifyInstallerIntegrity()) {
            // Installer has been tampered with - break functionality
            abort(503, 'System integrity check failed. Please contact support.');
        }

        return $next($request);
    }
}
