import { test, expect } from '@playwright/test';
import {
    BASE_URL,
    ADMIN,
    AUDITOR,
    loginAs,
    registerAndLogin,
    ensureLiveRacingEnabled,
    createArena,
    createEventShowUrl,
    addRace,
    addHorses,
    offerSingleBetTypes,
    publishEvent,
    placeWizardBet,
    adjustWalletAsAuditor,
} from '../helpers';

// Placing a Live Racing bet writes ONE "Bet" row per ticket to the player's
// wallet ledger (/transactions) for the whole wager, however many combos the
// ticket expanded into. See LiveRacingService::insertBetLedgerRow().

test.describe('Live Racing — bets in the wallet ledger', () => {
    test.setTimeout(240_000);

    test('a boxed Forecast writes one Bet row for the whole ticket', async ({ page }) => {
        const player = await registerAndLogin(page);
        await loginAs(page, AUDITOR.mobile, AUDITOR.password);
        await adjustWalletAsAuditor(page, player.mobile, '100', 'LR wallet ledger e2e');

        await loginAs(page, ADMIN.mobile, ADMIN.password);
        await ensureLiveRacingEnabled(page);
        const arena = await createArena(page, 'LRLedger', { forecast: '10' });
        const { eventUrl, eventId } = await createEventShowUrl(page, arena);
        const race = await addRace(page, eventUrl, 1);
        const [h1, h2] = await addHorses(page, race.raceUrl, 2);
        await offerSingleBetTypes(page, eventUrl, [{ key: 'forecast', raceId: race.raceId }]);
        await publishEvent(page, eventUrl);

        // Both horses in both positions -> 2 valid combos (1-2, 2-1) at ₱10 each.
        await loginAs(page, player.mobile, player.password);
        await placeWizardBet(page, {
            eventId,
            raceId: race.raceId,
            cardLabel: /^Forecast$/,
            positions: { 1: [h1, h2], 2: [h1, h2] },
            amount: '10',
        });

        await page.goto(`${BASE_URL}/transactions`);
        const betRows = page.locator('[data-testid^="transaction-row-"]', { hasText: 'Live Racing bet' });
        await expect(betRows).toHaveCount(1);

        // One ₱20 debit (2 combos x ₱10) taking the ₱100 adjustment down to ₱80.
        await expect(betRows.first()).toContainText('Bet');
        await expect(betRows.first()).toContainText('Forecast');
        await expect(betRows.first()).toContainText('(2 combos)');
        await expect(betRows.first()).toContainText('-₱20.00');
        await expect(betRows.first()).toContainText('₱80.00');

        // The adjustment that funded the wallet is still in the ledger below them.
        await expect(page.locator('[data-testid^="transaction-row-"]', { hasText: 'Adjustment' })).toHaveCount(1);
    });
});
