<?php

namespace App\Http\Middleware;

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

class BotAuthMiddleware
{
    /**
     * Validate requests from the Discord bot using a shared secret.
     * The bot must send:  Authorization: Bot <BOT_SECRET>
     */
    public function handle(Request $request, Closure $next): Response
    {
        $secret = config('services.discord.bot_secret');

        if (! $secret) {
            abort(500, 'BOT_SECRET not configured on server.');
        }

        $header = $request->header('Authorization');

        if (! $header || ! str_starts_with($header, 'Bot ')) {
            return response()->json(['error' => 'Missing or invalid Authorization header.'], 401);
        }

        $provided = substr($header, 4); // strip "Bot "

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

        return $next($request);
    }
}
