import { test, expect } from '@playwright/test';
import {
    BASE_URL,
    USER,
    ADMIN,
    SUPER_ADMIN,
    loginAs,
    ensureLiveRacingEnabled,
    createArena,
    createEventShowUrl,
    addRace,
    addHorses,
    offerSingleBetTypes,
    publishEvent,
    closeBetting,
    placeWizardBet,
    readWalletBalance,
} from '../helpers';

// The WFBO "Manual Settle" per-ticket action on /wfbo/live-racing/bets, gated
// to ROLE_SUPER_ADMIN. Covers: a bet left pending after a result is saved but
// never swept through the Settlements page can be graded from the bets page by
// a super-admin; a plain admin never sees the button.

test.describe.configure({ mode: 'serial' });

test.describe('Live Racing — SUPER_ADMIN manual settle per ticket', () => {
    test.setTimeout(180_000);

    test('super-admin settles a pending ticket from the bets page; plain admin cannot', async ({ page }) => {
        // ── Build a 1-race win event ────────────────────────────────────────
        await loginAs(page, ADMIN.mobile, ADMIN.password);
        await ensureLiveRacingEnabled(page);

        const arenaName = await createArena(page, 'LRManual', { win: '10' });
        const { eventUrl, eventId } = await createEventShowUrl(page, arenaName);
        const race = await addRace(page, eventUrl, 1);
        const horses = await addHorses(page, race.raceUrl, 4);
        await offerSingleBetTypes(page, eventUrl, [{ key: 'win', raceId: race.raceId }]);
        await publishEvent(page, eventUrl);

        const winner = horses[0];

        // ── Player backs the eventual winner ────────────────────────────────
        await loginAs(page, USER.mobile, USER.password);
        const balanceBefore = await readWalletBalance(page);
        await placeWizardBet(page, {
            eventId,
            raceId: race.raceId,
            cardLabel: /^Win$/,
            positions: { 1: [winner] },
        });

        // ── Admin records the result but does NOT run settlement ────────────
        // (saveResult only records finish order + dividends; the Settlements
        // page sweep is deliberately skipped so the bet stays pending.)
        await loginAs(page, ADMIN.mobile, ADMIN.password);
        await closeBetting(page, race.raceUrl);
        await page.goto(`${BASE_URL}${race.raceUrl}`);
        await page.selectOption('[data-testid="select-finisher-1"]', winner);
        await page.locator('[data-testid^="input-dividend-"]').first().fill('25.00');
        page.once('dialog', d => d.accept());
        await page.click('[data-testid="btn-save-result"]');
        await expect(page.locator('[data-testid="flash-success"]')).toBeVisible();

        // ── Plain admin: no manual-settle button on the bets page ───────────
        await page.goto(`${BASE_URL}/wfbo/live-racing/bets?event_id=${eventId}`);
        const row = page.locator('[data-testid^="live-racing-bet-row-"]').first();
        await expect(row).toBeVisible();
        const rowTestId = await row.getAttribute('data-testid');
        const ticketId = rowTestId!.replace('live-racing-bet-row-', '');
        await expect(page.locator(`[data-testid="btn-manual-settle-${ticketId}"]`)).toHaveCount(0);
        await expect(page.locator(`[data-testid="badge-status-${ticketId}"]`)).toHaveText('Pending');

        // ── Super-admin: settle the ticket inline ───────────────────────────
        await loginAs(page, SUPER_ADMIN.mobile, SUPER_ADMIN.password);
        await page.goto(`${BASE_URL}/wfbo/live-racing/bets?event_id=${eventId}`);

        const settleBtn = page.locator(`[data-testid="btn-manual-settle-${ticketId}"]`);
        await expect(settleBtn).toBeVisible();
        await settleBtn.click();

        const result = page.locator(`[data-testid="manual-settle-result-${ticketId}"]`);
        await expect(result).toContainText('won', { timeout: 20_000 });
        await expect(page.locator(`[data-testid="badge-status-${ticketId}"]`)).toHaveText('Won');

        // ── Player wallet credited exactly once ─────────────────────────────
        await loginAs(page, USER.mobile, USER.password);
        await page.goto(`${BASE_URL}/play/live-racing/history`);
        await expect
            .poll(() => readWalletBalance(page), { timeout: 15_000 })
            .toBeCloseTo(balanceBefore - 10 + 25, 1);
    });
});
