<?php
namespace App\Http\Middleware;

use App\Models\ApiKey;
use Closure;
use Illuminate\Http\Request;

class ApiKeyMiddleware
{
    public function handle(Request $request, Closure $next, string $permission = null)
    {
        $key = $request->header('X-API-Key') ?? $request->query('api_key');

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

        $apiKey = ApiKey::active()
            ->where('key', hash('sha256', $key))
            ->first();

        if (!$apiKey) {
            return response()->json(['error' => 'Invalid or inactive API key'], 401);
        }

        if ($apiKey->expires_at && $apiKey->expires_at->isPast()) {
            return response()->json(['error' => 'API key expired'], 401);
        }

        if ($permission && !$apiKey->hasPermission($permission)) {
            return response()->json(['error' => "Missing permission: {$permission}"], 403);
        }

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

        return $next($request);
    }
}
