<?php

namespace App\Http\Middleware;

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

class CheckApiKey
{
    public function handle(Request $request, Closure $next): Response
    {
        $key = $request->header('X-API-Key');
        $validKeys = array_filter(explode(',', config('app.api_keys', '')));

        if (empty($validKeys) || ! in_array($key, $validKeys, true)) {
            return response()->json([
                'success' => false,
                'message' => 'Akses tidak diizinkan',
            ], 401);
        }

        return $next($request);
    }
}
