<?php

namespace App\Http\Middleware;

use App\Services\ApiTokenService;
use Closure;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

class AuthenticateApiToken
{
    public function __construct(
        protected ApiTokenService $tokens,
    ) {}

    public function handle(Request $request, Closure $next): Response
    {
        $token = $this->tokens->findValid($request->bearerToken());

        if (! $token) {
            return new JsonResponse([
                'message' => 'Unauthenticated.',
            ], 401);
        }

        $user = $token->user;

        if (! $user || $user->status !== 'active') {
            return new JsonResponse([
                'message' => 'This account is inactive.',
            ], 403);
        }

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

        return $next($request);
    }
}
