<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

class VerifyPythonApiKey
{
    /**
     * Handle an incoming request.
     */
    public function handle(Request $request, Closure $next): Response
    {
        $apiKey = config('services.python_bridge.api_key');

        if (empty($apiKey)) {
            return response()->json([
                'status' => 'error',
                'error_code' => 'CONFIG_ERROR',
                'message' => 'API key not configured',
            ], 500);
        }

        $providedKey = $request->bearerToken();

        if (!$providedKey || !hash_equals($apiKey, $providedKey)) {
            return response()->json([
                'status' => 'error',
                'error_code' => 'AUTH_ERROR',
                'message' => 'Invalid or missing API key',
            ], 401);
        }

        // Optional: IP whitelist check
        $allowedIps = config('services.python_bridge.allowed_ips', []);
        if (!empty($allowedIps)) {
            $clientIp = $request->ip();
            if (!in_array($clientIp, $allowedIps)) {
                return response()->json([
                    'status' => 'error',
                    'error_code' => 'AUTH_ERROR',
                    'message' => 'IP not allowed',
                ], 403);
            }
        }

        return $next($request);
    }
}
