<?php

namespace App\Http\Middleware;

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

class AuthenticateApiKey
{
    /**
     * Handle an incoming request.
     *
     * @param  \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response)  $next
     */
    public function handle(Request $request, Closure $next): Response
    {
        $apiKey = $request->header('X-API-Key') ?: $request->query('api_key');

        if (!$apiKey) {
            return response()->json([
                'success' => false,
                'message' => 'API Key is not configured. First setup client API key configuration.',
            ], 401);
        }

        $hashedKey = hash('sha256', $apiKey);
        $client = ApiClient::where('api_key', $hashedKey)->first();

        if (!$client || !$client->is_active) {
            return response()->json([
                'success' => false,
                'message' => 'API Key is not configured. First setup client API key configuration.',
            ], 401);
        }

        // Attach client to request
        $request->attributes->set('api_client', $client);

        return $next($request);
    }
}
