<?php

namespace App\Http\Middleware;

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

class RequireAdminApiKey
{
    public function handle(Request $request, Closure $next): Response
    {
        $expected = (string) config('services.nusaclouds.admin_api_key');
        $provided = (string) $request->header('X-API-Key');

        if ($expected === '' || ! hash_equals($expected, $provided)) {
            return response()->json([
                'message' => 'Unauthorized.',
            ], 401);
        }

        return $next($request);
    }
}
