import { test, expect } from '@playwright/test';
import { BASE_URL, ADMIN, AGENT, SUPER_ADMIN, loginAs, configureLiveDraw, place2dBet, readWalletBalance, readUserWalletAsAdmin, manila } from '../helpers';

// Fixture player referred by the AGENT master (+10000000002).
const REFERRED = { mobile: '+10000000101', password: 'ReferralPass1!' };
// LiveDrawFixtures: yesterday's draw, never settled, one ₱20 Straight 03-04 bet by this player (₱1 commission to AGENT).
const YESTERDAY_BETTOR = '+10000000104';

test.describe('WFBO Live Draw ▸ 2D Draws', () => {

    test.afterAll(async ({ browser }) => {
        const page = await browser.newPage();
        await configureLiveDraw(page, { enabled: false, drawTime: '21:00', cutoff: '30', commission: '0' });
        await page.close();
    });

    test('the result cannot be declared while betting is open', async ({ page }) => {
        await configureLiveDraw(page, { enabled: true, drawTime: '23:59', cutoff: '1' });
        await loginAs(page, ADMIN.mobile, ADMIN.password);
        await page.goto(`${BASE_URL}/wfbo/live-draw/2d/draws`);

        const row = page.locator(`[data-testid="ld-draw-row-${manila(0).date}"]`);
        await expect(row).toContainText('Betting open');
        await row.locator('[data-testid^="ld-open-draw-"]').click();
        await expect(page.locator('[data-testid="ld-result-card"]')).toContainText('can be declared after the draw at');
        await expect(page.locator('[data-testid="ld-result-form"]')).toHaveCount(0);
    });

    test('the bet list can be searched by player, mobile, reference or the two numbers', async ({ page }) => {
        await loginAs(page, ADMIN.mobile, ADMIN.password);
        await page.goto(`${BASE_URL}/wfbo/live-draw/2d/draws`);
        await page.locator(`[data-testid="ld-draw-row-${manila(-24 * 60).date}"] [data-testid^="ld-open-draw-"]`).click();

        const rows    = page.locator('[data-testid="ld-bet-row"]');
        const summary = page.locator('[data-testid="ld-bet-search-summary"]');
        const searchFor = async (term: string) => {
            await page.fill('[data-testid="input-ld-bet-search"]', term);
            await page.press('[data-testid="input-ld-bet-search"]', 'Enter');
            await expect(summary).toContainText(term);
        };

        // LiveDrawFixtures: yesterday's draw holds one Straight 03-04 bet by Weekly Referral.
        await expect(rows).toHaveCount(1);
        await expect(rows.first()).toContainText('Straight 03-04');

        // The two numbers, typed in either order.
        await searchFor('03-04');
        await expect(rows).toHaveCount(1);
        await expect(rows.first()).toContainText('Straight 03-04');
        await searchFor('04-03');
        await expect(rows).toHaveCount(1);

        // A single number matches either position.
        await searchFor('03');
        await expect(rows).toHaveCount(1);

        // Player name, mobile, and bet reference.
        await searchFor('Weekly');
        await expect(rows).toHaveCount(1);
        await searchFor('+10000000104');
        await expect(rows).toHaveCount(1);
        await searchFor('LDFIXTUREYESTERDAY1');
        await expect(rows).toHaveCount(1);

        // No match: the table says so, and Clear brings every bet back.
        await searchFor('nothing-here');
        await expect(rows).toHaveCount(0);
        await expect(page.locator('[data-testid="ld-bets-empty"]')).toContainText('No bets match');

        await page.click('[data-testid="btn-ld-bet-search-clear"]');
        await expect(rows).toHaveCount(1);
        await expect(summary).toHaveCount(0);
    });

    test('the bet list filters by status, and the filter combines with the search', async ({ page }) => {
        await loginAs(page, ADMIN.mobile, ADMIN.password);
        await page.goto(`${BASE_URL}/wfbo/live-draw/2d/draws`);
        await page.locator(`[data-testid="ld-draw-row-${manila(-24 * 60).date}"] [data-testid^="ld-open-draw-"]`).click();

        const rows = page.locator('[data-testid="ld-bet-row"]');
        const empty = page.locator('[data-testid="ld-bets-empty"]');

        // LiveDrawFixtures: yesterday's draw holds one ₱20 Straight 03-04 bet, never graded.
        await expect(page.locator('[data-testid="ld-bet-filter-all"]')).toContainText('(1)');
        await expect(page.locator('[data-testid="ld-bet-filter-pending"]')).toContainText('(1)');
        await expect(page.locator('[data-testid="ld-bet-filter-won"]')).toContainText('(0)');
        await expect(page.locator('[data-testid="ld-bet-filter-lost"]')).toContainText('(0)');

        // Pending: the one bet.
        await page.click('[data-testid="ld-bet-filter-pending"]');
        await expect(page).toHaveURL(/status=pending/);
        await expect(rows).toHaveCount(1);
        await expect(rows.first()).toContainText('Straight 03-04');
        await expect(rows.first()).toContainText('Pending');

        // Won / Lose: nothing settled on this draw, so the table says which filter is empty.
        await page.click('[data-testid="ld-bet-filter-won"]');
        await expect(rows).toHaveCount(0);
        await expect(empty).toContainText('No bets with status “Won” on this draw.');

        await page.click('[data-testid="ld-bet-filter-lost"]');
        await expect(rows).toHaveCount(0);
        await expect(empty).toContainText('No bets with status “Lose” on this draw.');

        // The filter survives a search, and the search survives a filter change.
        await page.fill('[data-testid="input-ld-bet-search"]', '03-04');
        await page.click('[data-testid="btn-ld-bet-search"]');
        await expect(rows).toHaveCount(0);
        await expect(empty).toContainText('No bets match “03-04” with status “Lose”.');
        await expect(page.locator('[data-testid="ld-bet-filter-lost"]')).toHaveClass(/is-active/);

        await page.click('[data-testid="ld-bet-filter-pending"]');
        await expect(page.locator('[data-testid="input-ld-bet-search"]')).toHaveValue('03-04');
        await expect(rows).toHaveCount(1);

        // Clear drops the search but keeps the status pill selected.
        await page.click('[data-testid="btn-ld-bet-search-clear"]');
        await expect(page.locator('[data-testid="input-ld-bet-search"]')).toHaveValue('');
        await expect(page.locator('[data-testid="ld-bet-filter-pending"]')).toHaveClass(/is-active/);
        await expect(rows).toHaveCount(1);

        // Back to All.
        await page.click('[data-testid="ld-bet-filter-all"]');
        await expect(page).not.toHaveURL(/status=/);
        await expect(rows).toHaveCount(1);
    });

    test('an unsettled past draw is flagged, and a super admin can cancel it and refund every bet', async ({ page }) => {
        const playerBefore = await readUserWalletAsAdmin(page, YESTERDAY_BETTOR);
        const agentBefore  = await readUserWalletAsAdmin(page, AGENT.mobile);

        // The dashboard and 2D Draws both flag yesterday's draw.
        await page.goto(`${BASE_URL}/wfbo`);
        await expect(page.locator('[data-testid="dashboard-ld-needs-action"]')).toContainText('2D:');
        await page.goto(`${BASE_URL}/wfbo/live-draw/2d/draws`);
        await expect(page.locator('[data-testid="ld-needs-action"]')).toContainText('(declare the result)');

        // A plain admin can't cancel; a super admin can.
        const yesterday = page.locator(`[data-testid="ld-draw-row-${manila(-24 * 60).date}"]`);
        await yesterday.locator('[data-testid^="ld-open-draw-"]').click();
        await expect(page.locator('[data-testid="ld-void-card"]')).toHaveCount(0);
        const drawUrl = page.url();

        await loginAs(page, SUPER_ADMIN.mobile, SUPER_ADMIN.password);
        await page.goto(drawUrl);
        page.once('dialog', (d) => d.accept());
        await page.fill('[data-testid="ld-void-reason"]', 'No live stream (e2e)');
        await page.click('[data-testid="ld-btn-void"]');
        await expect(page.locator('[data-testid="ld-settlement-progress"]'))
            .toContainText('Draw cancelled: 1 bet(s) refunded (₱20.00), commission taken back.');
        await expect(page.locator('[data-testid="ld-void-note"]')).toBeVisible({ timeout: 15_000 });
        await expect(page.locator('[data-testid="ld-status"]').first()).toContainText('Cancelled');

        // Player got the ₱20 back; the agent's ₱1 commission was taken back; the alert is gone.
        expect(await readUserWalletAsAdmin(page, YESTERDAY_BETTOR)).toBeCloseTo(playerBefore + 20, 2);
        expect(await readUserWalletAsAdmin(page, AGENT.mobile)).toBeCloseTo(agentBefore - 1, 2);
        await page.goto(`${BASE_URL}/wfbo/live-draw/2d/draws`);
        await expect(page.locator('[data-testid="ld-needs-action"]')).toHaveCount(0);
    });

    test('declare the result, settle, and the winner is paid', async ({ page }) => {
        test.skip(manila(5).date !== manila(0).date, 'Too close to midnight');

        // Open betting, 5% master commission.
        await configureLiveDraw(page, { enabled: true, drawTime: '23:59', cutoff: '1', commission: '5' });

        const agentCommissionToday = async (): Promise<number> => {
            await loginAs(page, AGENT.mobile, AGENT.password);
            await page.goto(`${BASE_URL}/agent/dashboard`);
            const txt = (await page.locator('[data-testid="stat-agent-ldCommission"] .stat-value--lg').textContent()) ?? '';
            return parseFloat(txt.replace(/[^\d.-]/g, '')) || 0;
        };
        const commissionBefore = await agentCommissionToday();

        await loginAs(page, REFERRED.mobile, REFERRED.password);
        const before = await readWalletBalance(page);
        await place2dBet(page, 'straight', 9, 14, '10');
        await expect(page.locator('body')).toContainText('Straight 09-14 bet placed');
        await place2dBet(page, 'ramble', 1, 2, '5');
        await expect(page.locator('body')).toContainText('Ramble 01-02 bet placed');

        // Close betting: the draw time moves to now, so the cutoff has passed.
        await configureLiveDraw(page, { drawTime: manila(0).time, cutoff: '1' });

        await page.click('[data-testid="wfbo-nav-live-draw-2d-draws"]');
        const row = page.locator(`[data-testid="ld-draw-row-${manila(0).date}"]`);
        await expect(row).toContainText('Closed · waiting for result');
        await row.locator('[data-testid^="ld-open-draw-"]').click();

        await page.selectOption('[data-testid="ld-input-result1"]', '9');
        await page.selectOption('[data-testid="ld-input-result2"]', '14');
        await page.click('[data-testid="ld-btn-save-result"]');
        await expect(page.locator('[data-testid="flash-success"]')).toContainText('Result 09-14 saved');
        await expect(page.locator('[data-testid="ld-status"]').first()).toContainText('Resulted');

        await page.click('[data-testid="ld-btn-settle"]');
        await expect(page.locator('[data-testid="ld-settlement-progress"]')).toContainText(/Settled \d+ bet\(s\): 1 won, \d+ lost\. Total payout ₱6000\.00\./);
        await expect(page.locator('[data-testid="ld-status"]').first()).toContainText('Settled', { timeout: 15000 });
        await expect(page.locator('[data-testid="ld-kpi-payout"]')).toContainText('₱6,000.00');

        // The bet list labels a losing bet "Lose" (like the player pages), never "Lost".
        const betRows = page.locator('[data-testid="ld-bet-row"]');
        await expect(betRows).toHaveCount(2);
        await expect(betRows.first()).toContainText('Ramble 01-02');
        await expect(betRows.first()).toContainText('Lose');
        await expect(betRows.first()).not.toContainText('Lost');
        await expect(betRows.nth(1)).toContainText('Straight 09-14');
        await expect(betRows.nth(1)).toContainText('Won');

        // Status filter: one won, one lost.
        await expect(page.locator('[data-testid="ld-bet-filter-won"]')).toContainText('(1)');
        await expect(page.locator('[data-testid="ld-bet-filter-lost"]')).toContainText('(1)');
        await expect(page.locator('[data-testid="ld-bet-filter-pending"]')).toContainText('(0)');

        await page.click('[data-testid="ld-bet-filter-won"]');
        await expect(betRows).toHaveCount(1);
        await expect(betRows.first()).toContainText('Straight 09-14');
        await expect(betRows.first()).toContainText('Won');

        await page.click('[data-testid="ld-bet-filter-lost"]');
        await expect(betRows).toHaveCount(1);
        await expect(betRows.first()).toContainText('Ramble 01-02');
        await expect(betRows.first()).toContainText('Lose');

        await page.click('[data-testid="ld-bet-filter-all"]');
        await expect(betRows).toHaveCount(2);

        // Reports: today's 2D money is on the dashboard (cached ~30s), Games Report and Recent Bets.
        await expect.poll(async () => {
            await page.goto(`${BASE_URL}/wfbo?period=today`);
            return page.locator('[data-testid="stat-winAmount"]').innerText();
        }, { timeout: 60_000, intervals: [5_000] }).toContain('2D: ₱6,000.00');
        await expect(page.locator('[data-testid="stat-revenue"]')).toContainText('2D: ₱-');
        await page.goto(`${BASE_URL}/wfbo/games/report?period=today`);
        await expect(page.locator('[data-testid="games-report-row-ld"]')).toContainText('₱6,000.00');
        await page.goto(`${BASE_URL}/wfbo/recent-bets?category=live_draw`);
        await expect(page.locator('[data-testid="recent-bets-table"]')).toContainText('Straight 09-14');

        // Player: the Straight bet won ₱6,000 and the result is on the results page.
        await loginAs(page, REFERRED.mobile, REFERRED.password);
        expect(await readWalletBalance(page)).toBeCloseTo(before - 15 + 6000, 2);
        await page.goto(`${BASE_URL}/play/2d/history`);
        await expect(page.locator('[data-testid="ld-history-row"]').nth(1)).toContainText('Won');
        await expect(page.locator('[data-testid="ld-history-row"]').first()).toContainText('Lose');
        await page.goto(`${BASE_URL}/play/2d/results`);
        await expect(page.locator('[data-testid="ld-result-row"]').first()).toContainText('09');
        await expect(page.locator('[data-testid="ld-result-row"]').first()).toContainText('14');

        // Master agent: 5% of ₱15 = ₱0.75 more, paid when the bets were placed.
        expect(await agentCommissionToday()).toBeCloseTo(commissionBefore + 0.75, 2);
    });


    test('a super admin corrects a settled result and every bet is re-graded', async ({ page }) => {
        // Runs after the settle test: today's draw settled as 09-14 (Straight 09-14 ₱10 won, Ramble 01-02 ₱5 lost).
        await loginAs(page, REFERRED.mobile, REFERRED.password);
        const before = await readWalletBalance(page);

        await loginAs(page, SUPER_ADMIN.mobile, SUPER_ADMIN.password);
        await page.goto(`${BASE_URL}/wfbo/live-draw/2d/draws`);
        await page.locator(`[data-testid="ld-draw-row-${manila(0).date}"] [data-testid^="ld-open-draw-"]`).click();

        await page.selectOption('[data-testid="ld-correct-result1"]', '2');
        await page.selectOption('[data-testid="ld-correct-result2"]', '1');
        await page.fill('[data-testid="ld-correct-reason"]', 'Numbers misread (e2e)');
        page.once('dialog', (d) => d.accept());
        await page.click('[data-testid="ld-btn-correct"]');

        // 02-01: the Ramble 01-02 now wins (₱5 × 300), the Straight 09-14 win is taken back.
        await expect(page.locator('[data-testid="ld-settlement-progress"]'))
            .toContainText('Result corrected: 1 bet(s) now win (₱1500.00 paid), 1 no longer win (₱6000.00 taken back).');
        await expect(page.locator('[data-testid="ld-corrected-from"]')).toContainText('Corrected from 09-14', { timeout: 15_000 });
        await expect(page.locator('[data-testid="ld-result"]')).toContainText('02-01');

        await loginAs(page, REFERRED.mobile, REFERRED.password);
        expect(await readWalletBalance(page)).toBeCloseTo(before - 6000 + 1500, 2);
        await page.goto(`${BASE_URL}/play/2d/history`);
        await expect(page.locator('[data-testid="ld-history-row"]').first()).toContainText('Won');
        await expect(page.locator('[data-testid="ld-history-row"]').nth(1)).toContainText('Lose');
    });

});
