<?php

namespace App\Http\Middleware;

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

class ApiMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response)  $next
     */
    public function handle(Request $request, Closure $next): Response
    {
        // Get API key from header (e.g., apiKey: test)
        $apiKey = $request->header('apiKey');

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

        // Validate from database
        $key = ApiKey::where('key', $apiKey)
            ->where('status', 1)
            ->first();

        if (!$key) {
            return response()->json([
                'message' => 'Invalid or inactive API Key',
            ], 400);
        }

        // If valid, continue
        return $next($request);
    }
}
