<?php

namespace App\Http\Middleware;

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

class ApiTokenMiddleware
{
    /**
     * Authenticate API requests via ?token= query parameter.
     * The token must match a user's api_token column.
     */
    public function handle(Request $request, Closure $next): Response
    {
        $token = $request->query('token');

        if (!$token) {
            return response()->json([
                'success' => false,
                'message' => 'API token is required. Pass ?token=YOUR_TOKEN in the URL.',
            ], 401);
        }

        $user = User::where('api_token', $token)->first();

        if (!$user) {
            return response()->json([
                'success' => false,
                'message' => 'Invalid API token.',
            ], 401);
        }

        // Make the authenticated user available via $request->user()
        $request->merge(['_api_user' => $user]);
        $request->setUserResolver(fn() => $user);

        return $next($request);
    }
}
