import { test, expect, Page } from '@playwright/test';
import {
    BASE_URL,
    ADMIN,
    AUDITOR,
    SUPER_ADMIN,
    loginAs,
    registerAndLogin,
    adjustWalletAsAuditor,
    ensureLiveRacingEnabled,
    createArena,
    createEventShowUrl,
    addRace,
    addHorse,
    offerSingleBetTypes,
    publishEvent,
    closeBetting,
    saveResult,
    settleAndMarkRace,
    placeWizardBet,
} from '../helpers';

const DEFAULT_THRESHOLD = '20000.00';
const TEST_THRESHOLD    = '4.00';

/** Resolves an EventBetType id from a combination-entry block on a race's result form. */
async function dividendRowId(page: Page, label: string | RegExp): Promise<string> {
    const blocks = page.locator('[data-testid^="combo-bettype-"]');
    const count = await blocks.count();
    const hits: string[] = [];

    for (let i = 0; i < count; i++) {
        const block = blocks.nth(i);
        const text = (await block.locator('label.fw-semibold').first().textContent())
            ?.replace(/\s+/g, ' ')
            .replace(/\s*\([\d-]+…\)\s*$/u, '')
            .trim() ?? '';
        const hit = typeof label === 'string' ? text === label : label.test(text);
        if (hit) {
            const testId = await block.getAttribute('data-testid');
            hits.push(testId?.replace('combo-bettype-', '') ?? '');
        }
    }

    if (hits.length !== 1) {
        throw new Error(`Expected exactly one combination block for ${label}, found ${hits.length}`);
    }

    return hits[0];
}

async function saveAutoHoldSetting(page: Page, enabled: boolean, threshold: string): Promise<void> {
    await loginAs(page, SUPER_ADMIN.mobile, SUPER_ADMIN.password);
    await page.goto(`${BASE_URL}/wfbo/advanced-settings`);

    const toggle = page.locator('[data-testid="input-auto-hold-enabled"]');
    if ((await toggle.isChecked()) !== enabled) {
        await (enabled ? toggle.check() : toggle.uncheck());
    }
    await page.fill('[data-testid="input-auto-hold-threshold"]', threshold);
    await page.click('[data-testid="btn-save-advanced-settings"]');
    await expect(page.locator('[data-testid="flash-success"]')).toBeVisible();
}

test.describe('Daily win auto-hold', () => {
    test.setTimeout(240_000);

    test('holds a player who reaches the daily win threshold, then an admin can unhold them', async ({ page }) => {
        let player: { mobile: string; password: string } | undefined;

        try {
            // ── Configure the rule in WFBO ─────────────────────────────────
            await saveAutoHoldSetting(page, true, TEST_THRESHOLD);

            // Saved values round-trip.
            await page.reload();
            await expect(page.locator('[data-testid="input-auto-hold-enabled"]')).toBeChecked();
            await expect(page.locator('[data-testid="input-auto-hold-threshold"]')).toHaveValue(TEST_THRESHOLD);

            // New navigation entry.
            await expect(page.locator('[data-testid="wfbo-nav-on-hold"]')).toBeVisible();

            // ── Fund a fresh player ───────────────────────────────────────
            player = await registerAndLogin(page);
            await loginAs(page, AUDITOR.mobile, AUDITOR.password);
            await adjustWalletAsAuditor(page, player.mobile, '500', 'Daily win auto-hold e2e');

            // ── Build a published event with a Win bet on horse 1 ─────────
            await loginAs(page, ADMIN.mobile, ADMIN.password);
            await ensureLiveRacingEnabled(page);

            const arenaName = await createArena(page, 'AutoHold', { win: '50.00' });
            const { eventUrl, eventId } = await createEventShowUrl(page, arenaName);
            const raceNumber = Date.now() % 1000;
            const { raceUrl, raceId } = await addRace(page, eventUrl, raceNumber);
            const horses = [await addHorse(page, raceUrl, 1), await addHorse(page, raceUrl, 2)];

            await offerSingleBetTypes(page, eventUrl, [{ key: 'win', raceId }]);
            await publishEvent(page, eventUrl);

            // ── Player bets ₱50 and wins ₱5 (1 × 5.00), over the 4.00 rule ──
            await loginAs(page, player.mobile, player.password);
            await placeWizardBet(page, {
                eventId,
                raceId,
                cardLabel: 'Win',
                positions: { 1: [horses[0]] },
            });

            await loginAs(page, ADMIN.mobile, ADMIN.password);
            await closeBetting(page, raceUrl);
            await page.goto(`${BASE_URL}${raceUrl}`);

            const winId = await dividendRowId(page, /^Win$/);
            await saveResult(page, raceUrl, {
                combinations: { [winId]: [{ horseIds: [horses[0]], dividend: '5.00' }] },
            });
            await settleAndMarkRace(page, raceId);

            // ── The player is auto-held and shows on the On Hold page ─────
            await page.locator('[data-testid="wfbo-nav-on-hold"]').click();
            await expect(page).toHaveURL(/\/wfbo\/on-hold/);

            await page.fill('[data-testid="input-on-hold-search"]', player.mobile);
            await page.click('[data-testid="btn-on-hold-search"]');

            const row = page.locator('[data-testid^="on-hold-row-"]').filter({ hasText: player.mobile });
            await expect(row).toBeVisible();
            const userId = ((await row.getAttribute('data-testid')) ?? '').replace('on-hold-row-', '');
            await expect(page.locator(`[data-testid="on-hold-today-wins-${userId}"]`)).toContainText('5.00');
            await expect(page.locator(`[data-testid="on-hold-reason-${userId}"]`)).toContainText('Auto');

            // Restore the global threshold before the remaining assertions so
            // a later failure cannot leak it into other specs.
            await saveAutoHoldSetting(page, true, DEFAULT_THRESHOLD);

            // ── Admin unholds from the same page ─────────────────────────
            await page.goto(`${BASE_URL}/wfbo/on-hold?search=${encodeURIComponent(player.mobile)}`);
            await page.click(`[data-testid="btn-unhold-${userId}"]`);
            await expect(page.locator('[data-testid="flash-success"]')).toBeVisible();
            await expect(page.locator(`[data-testid="on-hold-row-${userId}"]`)).toBeHidden();
            await expect(page.locator('[data-testid="on-hold-empty"]')).toBeVisible();

            // The users list agrees: the On Hold badge is gone.
            await page.goto(`${BASE_URL}/wfbo/users?search=${encodeURIComponent(player.mobile)}`);
            await expect(page.locator(`[data-testid="badge-on-hold-${userId}"]`)).toHaveCount(0);
        } finally {
            // Best effort - never mask the real test failure.
            try {
                await saveAutoHoldSetting(page, true, DEFAULT_THRESHOLD);
            } catch {
                // ignore
            }
        }
    });
});
