<?php

namespace App\Http\Middleware;

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

/**
 * Live-domain re-verification — the domain-lock enforcer.
 *
 * `License::reverify()` runs here on real HTTP requests with the ACTUAL
 * `request()->getHost()`, so the verify server always sees the domain the app
 * is really running on (not the one frozen at activation). If a licensed
 * install is copied to a new domain, the server learns of it on the next daily
 * check and can reject → the app locks. (`License::reverify` self-throttles to
 * once per calendar day; network/5xx failures keep the last-good state.)
 *
 * Runs in `terminate()`, AFTER the response is sent, so the once-a-day network
 * call never adds latency to a user request. Dev hosts + unlicensed installs
 * are skipped. Fully defensive — never affects the response.
 */
class VerifyDomainLicense
{
    public function handle(Request $request, Closure $next): Response
    {
        return $next($request);
    }

    public function terminate(Request $request, Response $response): void
    {
        try {
            $host = $request->getHost();

            // Dev hosts are bypassed (and the server rubber-stamps them anyway);
            // nothing to re-verify if the install isn't licensed yet.
            if (License::isBypassed($host) || ! License::isLicensed()) {
                return;
            }

            // Reports the live host; reverify() throttles to once/day internally.
            License::reverify($host);
        } catch (\Throwable) {
            // Never let licensing telemetry affect a served request.
        }
    }
}
