/**
 * E2E：信用盘中奖结算 → game_settlement_win 释额 + 玩家流水 win_credit。
 */

import { test, expect } from '@playwright/test';
import {
  adminLoginViaBypass,
  e2e,
  fetchOpenDrawNo,
  playerLoginViaBypass,
  playerCtxOf,
  setupCreditPlayer,
} from './_helper';
import { runWalletDrawSettlement } from './helpers/draw-settlement';

test('信用玩家中奖结算 → credit_ledger game_settlement_win + 钱包流水 win_credit', async () => {
  test.setTimeout(240_000);

  const winNumber = `7${String(Date.now()).slice(-3)}`;
  const credit = await setupCreditPlayer({
    credit_limit: 100_000,
    username: `e2e_win_${Date.now()}`,
  });
  const drawNo = await fetchOpenDrawNo();

  const adminSession = await adminLoginViaBypass();
  const playerSession = await playerLoginViaBypass({
    site_code: credit.site_code,
    username: credit.username,
    password: credit.password,
  });

  await runWalletDrawSettlement({
    adminToken: adminSession.accessToken,
    playerToken: playerSession.access_token,
    drawNo,
    betNumber: winNumber,
    betAmount: 10_000,
    expectWalletIncrease: false,
  });

  const ledger = await e2e<any>(
    'GET',
    `/inspect/credit-ledger?player_id=${credit.player_id}&limit=20`,
  );
  const hold = ledger.data.rows.find((r: any) => r.reason === 'bet_hold');
  const winRow = ledger.data.rows.find((r: any) => r.reason === 'game_settlement_win');
  expect(hold, '下注后应有 bet_hold').toBeTruthy();
  expect(winRow, '中奖结算后应有 game_settlement_win').toBeTruthy();
  expect(Number(winRow.amount)).toBeGreaterThan(0);

  const ctx = await playerCtxOf(playerSession.access_token);
  const logs = await ctx.get('/api/v1/wallet/logs?page=1&size=20');
  expect(logs.ok()).toBeTruthy();
  const logsBody = (await logs.json()) as any;
  expect(logsBody.code).toBe(0);
  expect(logsBody.data.ledger_source).toBe('credit_ledger');
  const winLog = logsBody.data.items.find(
    (i: any) => i.biz_type === 'game_settlement_win' || i.type === 'win_credit',
  );
  expect(winLog, '玩家流水应展示中奖释额').toBeTruthy();
  await ctx.dispose();
});
