<?php

namespace App\Http\Middleware;

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

class ValidateApiKey
{
    /**
     * Handle an incoming request. Expects API key via:
     * - Authorization: Bearer {key}
     * - X-API-Key: {key}
     */
    public function handle(Request $request, Closure $next): Response
    {
        $key = $request->bearerToken()
            ?? $request->header('X-API-Key');

        if (!$key) {
            return response()->json(['message' => 'API key required.'], 401);
        }

        $prefix = substr($key, 0, 12);
        $apiKey = ApiKey::where('key_prefix', $prefix)->first();

        if (! $apiKey || ! $apiKey->isValidKey($key)) {
            return response()->json(['message' => 'Invalid API key.'], 401);
        }

        $apiKey->update(['last_used_at' => now()]);

        $request->setUserResolver(fn () => $apiKey->user);

        return $next($request);
    }
}

