<?php

declare(strict_types=1);

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

class EnforceQuota
{
    public function handle(Request $request, Closure $next): Response
    {
        $user = $request->user();

        if ($user === null) {
            // L'authentification est gérée en amont.
            return $next($request);
        }

        $quota = $user->monthlyTokenQuota();

        if ($quota !== null && $user->tokensUsedThisMonth() >= $quota) {
            $message = 'Quota mensuel de tokens atteint. Réessayez le mois prochain ou passez à un forfait supérieur.';

            if ($request->expectsJson() || str_contains((string) $request->header('Accept'), 'text/event-stream')) {
                return response(
                    'data: ' . json_encode(['error' => $message]) . "\n\n",
                    429,
                    ['Content-Type' => 'text/event-stream']
                );
            }

            return response()->json(['error' => $message], 429);
        }

        return $next($request);
    }
}
