<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;

class ValidateGameApiToken
{
    /**
     * Handle an incoming request.
     */
    public function handle(Request $request, Closure $next)
    {
        $token = $this->extractBearerToken($request);

        if (empty($token)) {
            logger()->warning('API Token validation failed - Token missing', [
                'ip' => $request->ip(),
                'endpoint' => $request->path(),
            ]);

            return response()->json([
                'status' => 'error',
                'error' => 'Missing API token. Provide token via "Authorization: Bearer <token>" header.',
            ], 401);
        }

        $expectedToken = config('game.tokens.discord.token', env('DISCORD_API_TOKEN', ''));

        if (empty($expectedToken) || ! hash_equals($expectedToken, $token)) {
            $maskedToken = substr($token, 0, 4).str_repeat('*', max(0, strlen($token) - 4));

            logger()->warning('API Token validation failed - Invalid token', [
                'ip' => $request->ip(),
                'endpoint' => $request->path(),
                'token_provided' => $maskedToken,
            ]);

            return response()->json([
                'status' => 'error',
                'error' => 'Invalid API token',
            ], 401);
        }

        return $next($request);
    }

    /**
     * Extract Bearer token from Authorization header.
     */
    protected function extractBearerToken(Request $request): ?string
    {
        // 1. Coba dari header Authorization (standard)
        $header = $request->header('Authorization');
        if (!empty($header) && str_starts_with($header, 'Bearer ')) {
            return substr($header, 7);
        }

        // 2. Fallback: Apache mod_rewrite bisa mengubah jadi REDIRECT_HTTP_AUTHORIZATION
        $redirectAuth = $_SERVER['REDIRECT_HTTP_AUTHORIZATION'] ?? '';
        if (!empty($redirectAuth) && str_starts_with($redirectAuth, 'Bearer ')) {
            return substr($redirectAuth, 7);
        }

        // 3. Fallback: coba dari getallheaders() (mod_php)
        if (function_exists('getallheaders')) {
            $allHeaders = getallheaders();
            if (isset($allHeaders['Authorization']) && str_starts_with($allHeaders['Authorization'], 'Bearer ')) {
                return substr($allHeaders['Authorization'], 7);
            }
            if (isset($allHeaders['authorization']) && str_starts_with($allHeaders['authorization'], 'Bearer ')) {
                return substr($allHeaders['authorization'], 7);
            }
        }

        return null;
    }
}
