/**
 * E2E：信用下注结算后关账 → 玩家账单 + 代理占成账单（share_profit）。
 */

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

test('关账后生成玩家账单与代理占成账单', async () => {
  test.setTimeout(300_000);

  const credit = await setupCreditPlayer({
    credit_limit: 100_000,
    username: `e2e_share_${Date.now()}`,
  });
  const drawNo = await fetchOpenDrawNo();

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

  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=50`,
  );
  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();

  const agentBills = billsBody.data.items.filter((b: any) => b.bill_type === 'agent');
  expect(agentBills.length, '关账后应生成代理占成账单').toBeGreaterThan(0);

  const leafEdge = agentBills.find(
    (b: any) =>
      Number(b.owner_id) === credit.agent_node_id || Number(b.counterparty_id) === credit.agent_node_id,
  );
  expect(leafEdge, '应包含直属代理节点的占成边').toBeTruthy();

  const meta =
    typeof leafEdge.meta_json === 'string'
      ? JSON.parse(leafEdge.meta_json)
      : leafEdge.meta_json ?? {};
  expect(
    'share_profit' in meta || Number(leafEdge.net_amount) !== 0,
    '代理账单应含占成信息或非零净额',
  ).toBeTruthy();

  await admin.dispose();
});
