<?php

namespace App\Http\Middleware;

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

class VerifyApiKey
{
    public function handle(Request $request, Closure $next)
    {
        $apiKey = $request->header('X-API-KEY') ?: $request->query('api_key');

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

        $key = UserApiKey::where('key', $apiKey)->where('is_active', true)->first();

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

        // Rate limit check
        $calls = $key->apiCallLogs()->where('created_at', '>', now()->subMinute())->count();
        if ($calls >= $key->rate_limit_per_minute) {
            return response()->json(['error' => 'Rate limit exceeded'], 429);
        }

        $request->merge(['api_key_record' => $key]);

        return $next($request);
    }
}