<?php

namespace App\Http\Controllers\Api\V1\Admin\Player;

use App\Models\Player;
use App\Models\PlayerWallet;
use App\Support\ApiResponse;
use App\Support\AdminSiteScope;
use Illuminate\Http\JsonResponse;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;

/**
 * 后台：按玩家查询钱包余额（`player_wallets` 全币种）。
 *
 * 路由：`GET /api/v1/admin/players/{player}/wallets`
 */
final class PlayerWalletShowController extends Controller
{
    public function __invoke(Request $request, Player $player): JsonResponse
    {
        $admin = $request->lotteryAdmin();
        abort_if($admin === null, 401);

        if ($denied = AdminSiteScope::denyUnlessPlayerAccessible($admin, $player)) {
            return $denied;
        }

        $wallets = PlayerWallet::query()
            ->where('player_id', $player->id)
            ->orderBy('wallet_type')
            ->orderBy('currency_code')
            ->get();

        $rows = $wallets->map(static function (PlayerWallet $w): array {
            $bal = (int) $w->balance;
            $frozen = (int) $w->frozen_balance;

            return [
                'id' => $w->id,
                'wallet_type' => $w->wallet_type,
                'currency_code' => $w->currency_code,
                'balance' => $bal,
                'frozen_balance' => $frozen,
                'available_balance' => max(0, $bal - $frozen),
                'status' => (int) $w->status,
                'version' => (int) $w->version,
            ];
        })->values()->all();

        return ApiResponse::success([
            'player' => [
                'id' => $player->id,
                'site_code' => $player->site_code,
                'site_player_id' => $player->site_player_id,
                'username' => $player->username,
                'nickname' => $player->nickname,
                'default_currency' => $player->default_currency,
                'status' => (int) $player->status,
            ],
            'wallets' => $rows,
        ]);
    }
}
