<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;

class SystemApiKey
{
    public function handle(Request $request, Closure $next)
    {
        $configured = (string) config('rewards.system_api_key');
        $provided = (string) $request->header('X-Basketloot-Key');

        if ($configured === '' || $provided === '' || !hash_equals($configured, $provided)) {
            return response()->json([
                'error' => ['code' => 'unauthorized', 'message' => 'A valid X-Basketloot-Key header is required.'],
            ], 401);
        }

        return $next($request);
    }
}
