<?php

namespace App\Http\Middleware;

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

class InternalApiToken
{
    public function handle(Request $request, Closure $next): Response
    {
        $expected = (string) env('INTERNAL_API_TOKEN', '');

        if ($expected === '') {
            return response()->json([
                'success' => false,
                'error' => 'INTERNAL_API_TOKEN not configured',
            ], 500);
        }

        $provided = (string) $request->header('X-Internal-Token', '');

        if (!hash_equals($expected, $provided)) {
            return response()->json([
                'success' => false,
                'error' => 'Unauthorized',
            ], 401);
        }

        return $next($request);
    }
}

