<?php

namespace App\Http\Middleware;

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

/**
 * License Guard Middleware
 *
 * Performs periodic license validation without blocking user experience
 * Uses graceful degradation approach
 */
class LicenseGuard
{
    protected LicenseService $licenseService;

    public function __construct(LicenseService $licenseService)
    {
        $this->licenseService = $licenseService;
    }

    /**
     * Handle an incoming request
     */
    public function handle(Request $request, Closure $next): Response
    {
        // Skip for installer routes
        if ($request->is('install/*') || $request->is('invalid-license') || $request->is('verify-purchase')) {
            return $next($request);
        }

        // Skip if app is not installed
        if (!env('APP_INSTALL', false)) {
            return $next($request);
        }

        // Skip for API/webhook routes that shouldn't be blocked
        if ($request->is('api/webhooks/*')) {
            return $next($request);
        }

        // Check license validity
        if (!$this->licenseService->isLicenseValid()) {
            \Log::warning('License validation failed for request', [
                'route' => $request->path(),
                'user_id' => auth()->id()
            ]);

            // Check if domain integrity is maintained
            if (!$this->licenseService->validateDomainIntegrity()) {
                return $this->handleInvalidLicense($request, 'Domain verification failed. License is bound to different domain.');
            }

            return $this->handleInvalidLicense($request, 'Your license requires verification. Please contact support.');
        }

        // Randomly trigger background verification (1% chance on each request)
        // This distributes verification across time without impacting performance
        if (rand(1, 100) === 1) {
            $this->triggerBackgroundVerification();
        }

        return $next($request);
    }

    /**
     * Handle invalid license
     */
    private function handleInvalidLicense(Request $request, string $message): Response
    {
        if ($request->expectsJson()) {
            return response()->json([
                'error' => 'License verification required',
                'message' => $message
            ], 403);
        }

        return redirect()->route('invalid.purchase', ['verification_view' => true])
            ->with('error', $message);
    }

    /**
     * Trigger background verification asynchronously
     */
    private function triggerBackgroundVerification(): void
    {
        try {
            // Use Laravel's queue for async verification if available
            if (config('queue.default') !== 'sync') {
                dispatch(function () {
                    $this->licenseService->periodicVerification();
                })->onQueue('low');
            }
        } catch (\Exception $e) {
            \Log::error('Background verification dispatch failed', [
                'error' => $e->getMessage()
            ]);
        }
    }
}
