<?php

declare(strict_types=1);

namespace App\Http\Middleware;

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

/**
 * EnforceLicense — JWT-cache backed license gate.
 *
 * - isDevMode bypass (localhost/local/testing)
 * - license.* + admin.license.* + login + assets her zaman erişilebilir
 * - JSON istekler için 402 + buy_url
 * - HTML istekler için /lisans/satin-al redirect (Task 9'da route oluşacak)
 * - Feature gate (middleware param ile)
 */
class EnforceLicense
{
    public function __construct(private LicenseManager $manager) {}

    public function handle(Request $request, Closure $next, ?string $feature = null): Response
    {
        // Always-allowed routes: license.*, login, logout, assets — JWT kontrolü atlanır
        // (dev mode bypass artık LicenseManager içinde; JWT yoksa redirect yapılır)
        if ($this->isAllowedWhenInvalid($request)) {
            return $next($request);
        }

        if (! $this->manager->isValid()) {
            if ($request->expectsJson()) {
                return response()->json([
                    'error' => 'license_required',
                    'message' => 'Onoxsoft Panel lisansı gerekli',
                    'buy_url' => $this->buyUrl(),
                ], 402);
            }

            return redirect()->to($this->buyUrl());
        }

        if ($feature && ! $this->manager->hasFeature($feature)) {
            if ($request->expectsJson()) {
                return response()->json(['error' => 'feature_locked', 'feature' => $feature], 402);
            }
            abort(402, "Bu özellik için lisans yükseltmesi gerekir: {$feature}");
        }

        return $next($request);
    }

    private function isAllowedWhenInvalid(Request $request): bool
    {
        return $request->routeIs('license.*')
            || $request->routeIs('admin.license.*')
            || $request->routeIs('login')
            || $request->routeIs('logout')
            || $request->routeIs('password.*')
            || str_starts_with($request->path(), 'build/')
            || str_starts_with($request->path(), 'images/')
            || str_starts_with($request->path(), 'storage/')
            || $request->path() === 'favicon.ico'
            || $request->path() === 'up';
    }

    private function buyUrl(): string
    {
        try {
            return route('license.buy');
        } catch (\Throwable) {
            return '/lisans/satin-al';  // Task 9 oluşturana kadar fallback
        }
    }
}
