<?php

namespace App\Http\Middleware;

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

/**
 * Hard license gate. Until a valid Envato purchase code is activated, every
 * app route redirects to the standalone `/license/verify` screen.
 *
 * Registered in bootstrap/app.php `web(prepend:)` IMMEDIATELY AFTER
 * RequireInstall — a fresh install must reach the wizard first; once
 * installed, the license gate kicks in.
 *
 * Bypassed (never locked):
 *   - dev hosts (localhost / 127.0.0.1 / *.test / *.local / *ngrok*)
 *   - the LICENSE_ENFORCE=false vendor/demo kill-switch
 * Always allowed through (so the gate is reachable + escapable):
 *   - the license.* routes themselves (verify screen + activate POST)
 *
 * JSON / fetch callers get a 403 {message} so an SPA fetch doesn't render the
 * raw license screen; Inertia + plain browsers get a redirect.
 */
class EnforceLicense
{
    public function handle(Request $request, Closure $next): Response
    {
        if (License::isBypassed($request->getHost())) {
            return $next($request);
        }

        // The license screen + its activate POST must always be reachable,
        // or the gate would redirect-loop onto itself. The install wizard is
        // also always allowed — installation must complete before the license
        // gate applies (RequireInstall runs first, but it passes through once
        // the lock file exists, so re-running the wizard or completing it must
        // never bounce to the license screen).
        if (
            $request->routeIs('license.*')
            || $request->is('license/verify')
            || $request->is('license/activate')
            || $request->is('install')
            || $request->is('install/*')
        ) {
            return $next($request);
        }

        if (License::isLicensed()) {
            return $next($request);
        }

        // Pure JSON/fetch callers (not Inertia) expect JSON, not an HTML
        // redirect they can't follow into a rendered page.
        if ($request->expectsJson() && ! $request->hasHeader('X-Inertia')) {
            return response()->json(['message' => 'License activation required.'], 403);
        }

        return redirect()->route('license.verify');
    }
}
