<?php

namespace App\Http\Middleware;

use App\Models\FiveMServer;
use Closure;
use Illuminate\Http\Request;
use Laravel\Sanctum\PersonalAccessToken;
use Symfony\Component\HttpFoundation\Response;

/**
 * Authenticates FiveM Lua resources against a dedicated server API token —
 * deliberately separate from the dashboard's Sanctum "web" guard so a
 * leaked player/admin session or a leaked server token can never be used
 * to impersonate the other. Tokens are issued per-server from the admin
 * panel (Admin\ServerTokenController) and can be revoked independently.
 */
class AuthenticateFiveMApiToken
{
    public function handle(Request $request, Closure $next): Response
    {
        $bearer = $request->bearerToken();

        if (! $bearer) {
            abort(401, 'Missing API token.');
        }

        $accessToken = PersonalAccessToken::findToken($bearer);

        if (! $accessToken || ! $accessToken->tokenable instanceof FiveMServer) {
            abort(401, 'Invalid API token.');
        }

        $server = $accessToken->tokenable;

        if (! $server->is_active) {
            abort(403, 'This server token has been disabled.');
        }

        $accessToken->forceFill(['last_used_at' => now()])->save();

        $request->attributes->set('fivem_server', $server);

        return $next($request);
    }
}
