<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;
use App\Models\Endpoint;
use Illuminate\Support\Facades\Log;
class EndpointTokenMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response)  $next
     */
    public function handle(Request $request, Closure $next): Response
    {
        $token = $request->header('token-endpoint');
        if(!$token){
            Log::error('token-endpoint');
            Log::error('Token endpoint non trovato');
            Log::error('Request: ' . json_encode($request->all()));
            Log::error('Headers: ' . json_encode($request->header()));
            return response()->json(['message' => 'Token endpoint non trovato', 'status' => 'error', 'success' => false], 401);
        }
        $endpoint = Endpoint::where('token', $token)->first();
        if(!$endpoint){
            Log::error('token-endpoint');
            Log::error('Endpoint non trovato con token ' . $token);
            Log::error('Request: ' . json_encode($request->all()));
            return response()->json(['message' => 'Endpoint non trovato con token ' . $token, 'status' => 'error', 'success' => false], 404);
        }
        $request->merge(['endpoint' => $endpoint]);
        return $next($request);
    }
}
