<?php

namespace App\Http\Middleware;

use App\Models\api\v1\ApiKey;
use App\Services\ApiKeyService;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Notifications\Action;
use League\Config\ReadOnlyConfiguration;
use Symfony\Component\HttpFoundation\Response;

class VerifyFastApiKey
{
    /**
     * Handle an incoming request.
     *
     * @param  \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response)  $next
     */
    public function handle(Request $request, Closure $next): Response
    {
//        //verification de la clé de l API avant execution de chaque requete
//        $apiKey = config('app.fast_api_key');
//        $apiKeyIsValid = (
//            !empty($apiKey)
//            && $request->header('x-api-key') == $apiKey
//        );

        $api_key = ApiKey::where([['key', $request->header('x-api-key')] , ['is_active', 1]])->first();
        if (!$api_key)
        {
            return response()->json(["success" => false, "message" => "Access denied", "data"=>[]], 401);
        }

        ApiKeyService::setApiKey($request, $api_key);

        return $next($request);
    }
}