<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;
use App\Models\ApiToken;
use App\Models\User;

class AuthenticateWithToken
{
    /**
     * Handle an incoming request.
     *
     * @param  \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response)  $next
     */
    public function handle(Request $request, Closure $next): Response
    {
        $header = $request->header('Authorization');

        if (! $header || ! str_starts_with($header, 'Bearer ')) {
            return response()->json(['message' => 'Unauthorized'], 401);
        }

        $plainToken = substr($header, 7);
        $hashedToken = hash('sha256', $plainToken);

        $tokenRecord = ApiToken::where('token', $hashedToken)->first();

        if (! $tokenRecord) {
            return response()->json(['message' => 'Unauthorized'], 401);
        }

        // Load user from token
        $user = User::find($tokenRecord->user_id);

        if (! $user) {
            return response()->json(['message' => 'Unauthorized'], 401);
        }

        // Set authenticated user
        // auth()->setUser($user);
        $request->setUserResolver(fn () => $user);

        return $next($request);
    }
}
