<?php

namespace App\Http\Middleware;

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

class CheckLicense
{
    public function __construct(protected LicenseClientService $license)
    {
    }

    public function handle(Request $request, Closure $next): Response
    {
        if ($request->routeIs('licenses.setup', 'licenses.activate')) {
            return $next($request);
        }

        $current = $this->license->getCurrent();

        if (! $current) {
            return redirect()->route('licenses.setup');
        }

        $result = $this->license->verify($current);

        if (! $result['ok']) {
            session()->flash('license_error', $result['message'] ?? 'Lisensi tidak valid.');
            return redirect()->route('licenses.setup');
        }

        return $next($request);
    }
}
