/**
 * E2E：代理账期开账 → 信用注单结算 → 关账出玩家账单。
 */

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

test('信用下注结算后关账 → 生成玩家 settlement_bill', async () => {
  test.setTimeout(240_000);

  const credit = await setupCreditPlayer({ credit_limit: 100_000 });
  const drawNo = await fetchOpenDrawNo();

  const adminSession = await adminLoginViaBypass();
  const admin = await adminCtxOf(adminSession.accessToken);
  const periodId = await openSettlementPeriod(admin, credit.admin_site_id, credit.site_code);

  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: '5678',
    betAmount: 10_000,
    expectWalletIncrease: false,
  });

  const close = await admin.post(`/api/v1/admin/settlement-periods/${periodId}/close`);
  expect(close.ok(), `close period status=${close.status()}`).toBeTruthy();
  const closeBody = (await close.json()) as any;
  expect(closeBody.code).toBe(0);

  const bills = await admin.get(
    `/api/v1/admin/settlement-bills?settlement_period_id=${periodId}&size=20`,
  );
  const billsBody = (await bills.json()) as any;
  expect(billsBody.code).toBe(0);
  const playerBill = billsBody.data.items.find(
    (b: any) => b.bill_type === 'player' && Number(b.owner_id) === credit.player_id,
  );
  expect(playerBill, '应有该信用玩家的账单').toBeTruthy();

  await admin.dispose();
});
