<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Http\Requests\Api\RoleInfoRequest;
use App\Http\Resources\BaseResource;
use App\Services\Api\API;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

final class GameApiController extends Controller
{
    public function __construct(
        private API $api,
    ) {}

    protected function errorResponse(string $message, int $status = 400): JsonResponse
    {
        return BaseResource::makeEnvelope(
            resource: null,
            success: false,
            error: $message,
            status: $status,
        );
    }

    protected function successResponse(array $data): JsonResponse
    {
        return BaseResource::makeEnvelope(resource: $data);
    }

    /**
     * Extract Bearer token from Authorization header.
     */
    protected function extractBearerToken(Request $request): ?string
    {
        $header = $request->header('Authorization');

        if (empty($header)) {
            return null;
        }

        if (str_starts_with($header, 'Bearer ')) {
            return substr($header, 7);
        }

        return null;
    }

    /**
     * Validate API Token.
     */
    public function validate(Request $request): JsonResponse
    {
        $token = $this->extractBearerToken($request);

        if (empty($token)) {
            return $this->errorResponse('Missing API token. Use "Authorization: Bearer <token>" header.', 401);
        }

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

        if (empty($expectedToken) || ! hash_equals($expectedToken, $token)) {
            return $this->errorResponse('Invalid API token', 401);
        }

        return $this->successResponse([
            'message' => 'Token valid',
            'permission' => 'read',
            'description' => 'Discord RPC client - read only access',
        ]);
    }

    /**
     * Get Online Players.
     */
    public function playerOnline(): JsonResponse
    {
        $onlineUsers = $this->api->getOnlineList();

        return $this->successResponse([
            'online_count' => count($onlineUsers),
            'players' => $onlineUsers,
        ]);
    }

    /**
     * Get Character Info.
     */
    public function roleInfo(RoleInfoRequest $request): JsonResponse
    {
        $roleId = $request->getRoleId();

        $role = $this->api->getRole($roleId);
        $factionInfo = $this->api->getUserFaction($roleId);
        $factionId = $factionInfo['fid'] ?? null;
        $factionName = 'None Faction';

        if ($factionId) {
            $factionData = $this->api->getFactionInfo($factionId);
            if (! empty($factionData['name'])) {
                $factionName = $factionData['name'];
            }
        }

        return $this->successResponse([
            'name' => $role['base']['name'] ?? '',
            'level' => $role['status']['level'] ?? 0,
            'cls' => $role['base']['cls'] ?? 0,
            'faction' => $factionName,
            'faction_role' => $factionInfo['role'] ?? 0,
            'reputation' => $role['status']['reputation'] ?? 0,
            'money' => $role['pocket']['money'] ?? 0,
        ]);
    }
}
