<?php

namespace App\Http\Middleware;

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

class ApiTokenAuth
{
    public function handle(Request $request, Closure $next)
    {
        $header = $request->header('Authorization', '');
        if (! str_starts_with($header, 'Bearer ')) {
            return $this->unauthorizedResponse('missing_bearer');
        }
        $token = substr($header, 7);
        $userId = Cache::get('api_token:'.$token);
        if (! $userId) {
            return $this->unauthorizedResponse('token_unknown');
        }
        $user = User::find($userId);
        if (! $user) {
            return $this->unauthorizedResponse('user_missing');
        }
        Auth::login($user); // for policies if needed

        return $next($request);
    }

    private function unauthorizedResponse(string $reason): JsonResponse
    {
        return ApiError::response(
            'unauthorized',
            'Unauthorized',
            'Authentication is required to access this resource.',
            Response::HTTP_UNAUTHORIZED,
            ['reason' => $reason]
        );
    }
}
