/**
 * E2E：信用盘下注占用授信，钱包余额不变。
 */

import { test, expect } from '@playwright/test';
import {
  fetchOpenDrawNo,
  playerLoginViaBypass,
  setupCreditPlayer,
  e2e,
} from './_helper';

const CURRENCY = (process.env.LOTTERY_DEFAULT_CURRENCY ?? 'NPR').toUpperCase();
const BET_AMOUNT = 10_000;

test('信用玩家下注 → used_credit 增加、钱包 balance 不变', async () => {
  const credit = await setupCreditPlayer({ credit_limit: 50_000 });
  const drawNo = await fetchOpenDrawNo();

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

  const ctx = await (await import('./_helper')).playerCtxOf(session.access_token);
  const bal0 = (await (await ctx.get('/api/v1/wallet/balance')).json()) as any;
  const walletBefore = Number(bal0.data.balance);

  const place = await ctx.post('/api/v1/ticket/place', {
    data: {
      draw_id: drawNo,
      currency_code: CURRENCY,
      client_trace_id: `e2e-credit-${Date.now()}`,
      lines: [{ number: '1234', play_code: 'straight', amount: BET_AMOUNT }],
    },
  });
  expect(place.ok()).toBeTruthy();
  const body = (await place.json()) as any;
  expect(body.code).toBe(0);

  const bal1 = (await (await ctx.get('/api/v1/wallet/balance')).json()) as any;
  expect(Number(bal1.data.balance)).toBe(walletBefore);
  await ctx.dispose();

  const inspect = await e2e<any>('GET', `/inspect/credit-ledger?player_id=${credit.player_id}&limit=5`);
  expect(inspect.data.count).toBeGreaterThan(0);
  const hold = inspect.data.rows.find((r: any) => r.reason === 'bet_hold');
  expect(hold).toBeTruthy();
});
