/**
 * E2E：Reverb balance.update 广播（transfer-in 触发）。
 */

import { test, expect } from '@playwright/test';
import { createRequire } from 'node:module';
import {
  playerLoginViaBypass,
  resetE2EPlayer,
  resetWalletMock,
  setMockWalletMode,
  sleep,
} from './_helper';

test.beforeEach(async () => {
  await resetWalletMock();
  await setMockWalletMode('success');
});

const require = createRequire(import.meta.url);
const { Pusher } = require('pusher-js') as { Pusher: new (key: string, opts: Record<string, unknown>) => any };

const CURRENCY = (process.env.LOTTERY_DEFAULT_CURRENCY ?? 'NPR').toUpperCase();
const REVERB_KEY = process.env.REVERB_APP_KEY ?? 'e2e-key';
const REVERB_HOST = process.env.REVERB_HOST ?? '127.0.0.1';
const REVERB_PORT = Number(process.env.REVERB_PORT ?? 8080);

test('transfer-in 后收到 balance.update WebSocket 事件', async () => {
  test.setTimeout(60_000);
  await resetE2EPlayer();
  const session = await playerLoginViaBypass();
  const playerId = session.player.id;

  const events: any[] = [];
  const pusher = new Pusher(REVERB_KEY, {
    wsHost: REVERB_HOST,
    wsPort: REVERB_PORT,
    forceTLS: false,
    disableStats: true,
    enabledTransports: ['ws'],
    cluster: 'mt1',
  });

  const channel = pusher.subscribe(`player.${playerId}`);
  channel.bind('balance.update', (data: unknown) => {
    events.push(data);
  });

  await sleep(500);

  const ctx = await (await import('./_helper')).playerCtxOf(session.access_token);
  const r = await ctx.post('/api/v1/wallet/transfer-in', {
    data: {
      amount: 20_000,
      currency: CURRENCY,
      idempotent_key: `e2e-bcast-${Date.now()}`,
    },
  });
  expect(r.ok()).toBeTruthy();
  await ctx.dispose();

  for (let i = 0; i < 30 && events.length === 0; i++) {
    await sleep(500);
  }

  pusher.disconnect();
  expect(events.length).toBeGreaterThan(0);
  expect(events[0].reason).toBeTruthy();
});
