<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Cache;

class LicenseMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response)  $next
     */
    public function handle(Request $request, Closure $next): Response
    {
        $licenseKey = session('license_key');
        $domain = session('domain');

        if (!$licenseKey || !$domain) {
            return redirect()->route('install.index')->withErrors(['message' => 'Lütfen önce kurulumu tamamlayın.']);
        }

        // Cache the validation result for 60 minutes to avoid hitting the license server on every request
        $validationData = Cache::remember("license_{$licenseKey}", 60, function () use ($licenseKey, $domain) {
            try {
                // In production, use env('LICENSE_SERVER_URL')
                $response = Http::post('http://localhost:8000/api/license/validate', [
                    'license_key' => $licenseKey,
                    'domain' => $domain,
                ]);

                if ($response->successful()) {
                    return $response->json();
                }
            } catch (\Exception $e) {
                // Log exception
            }

            return null;
        });

        if (!$validationData || $validationData['status'] !== 'success') {
            Cache::forget("license_{$licenseKey}");
            return response()->view('errors.license_invalid', ['message' => $validationData['message'] ?? 'Lisans doğrulanamadı.']);
        }

        // Share the plan constraints with all views
        view()->share('license_plan', $validationData['data']['plan']);
        view()->share('license_end_date', $validationData['data']['end_date']);

        return $next($request);
    }
}
