<?php

namespace App\Http\Middleware;

use App\Models\ApiToken;
use Closure;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Symfony\Component\HttpFoundation\Response;

class AuthenticateApiToken
{
    public function handle(Request $request, Closure $next): Response
    {
        $plainToken = $request->bearerToken();

        if (!$plainToken) {
            return new JsonResponse(['message' => 'Unauthorized'], 401);
        }

        $hash = hash('sha256', $plainToken);
        $token = ApiToken::with('user')->where('token_hash', $hash)->first();

        if (!$token || !$token->user) {
            return new JsonResponse(['message' => 'Unauthorized'], 401);
        }

        if ($token->expires_at && $token->expires_at->isPast()) {
            $token->delete();

            return new JsonResponse(['message' => 'Token expired'], 401);
        }

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

        Auth::setUser($token->user);
        $request->setUserResolver(static fn () => $token->user);
        $request->attributes->set('api_token', $token);

        return $next($request);
    }
}
