import { test, expect, type Page } from '@playwright/test';
import { BASE_URL, USER, SUPER_ADMIN, SUB_AGENT, loginAs, configureLiveDraw, place2dBet, readWalletBalance, manila } from '../helpers';

// Fixture player (referred by the AGENT master) used as the test account.
const TESTER = { mobile: '+10000000103', password: 'ReferralPass1!' };

/** Flags a user as a test account via WFBO ▸ Users (super admin only). */
async function markTestAccount(page: Page, mobile: string): Promise<void> {
    await loginAs(page, SUPER_ADMIN.mobile, SUPER_ADMIN.password);
    await page.goto(`${BASE_URL}/wfbo/users?search=${encodeURIComponent(mobile)}`);
    const row = page.locator('[data-testid^="user-row-"]').filter({ hasText: mobile });
    const id  = (await row.getAttribute('data-testid'))!.replace('user-row-', '');
    await page.locator(`[data-testid="form-enable-test-account-${id}"]`).evaluate((f: HTMLFormElement) => f.submit());
    await expect(page.locator(`[data-testid="badge-test-account-${id}"]`)).toBeVisible();
}

test.describe('2D (Live Draw) — player', () => {

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

    test('player places Straight and Ramble bets and sees them in Bet History', async ({ page }) => {
        await configureLiveDraw(page, { enabled: true, drawTime: '23:59', cutoff: '1' });
        await loginAs(page, USER.mobile, USER.password);

        await page.goto(`${BASE_URL}/`);
        await expect(page.locator('[data-testid="play-2d-card"]')).toBeVisible();
        await page.click('[data-testid="play-2d-card"]');
        await expect(page).toHaveURL(/\/play\/2d/);
        await expect(page.locator('[data-testid="ld-draw-card"]')).toContainText('11:59 PM');

        const before = await readWalletBalance(page);

        // Straight 07-21 for ₱10: possible win ₱6,000.
        await page.click('[data-testid="ld-type-straight"]');
        await page.click('[data-testid="ld-num-7"]');
        await page.click('[data-testid="ld-num-21"]');
        await page.fill('[data-testid="ld-amount"]', '10');
        await expect(page.locator('[data-testid="ld-possible-win"]')).toHaveText('₱6,000.00');
        await page.click('[data-testid="ld-btn-place-bet"]');
        await expect(page.locator('[data-testid="flash-success"]')).toContainText('Straight 07-21 bet placed');

        // Ramble 21-07 for ₱20: possible win ₱6,000 (300 × 20).
        await place2dBet(page, 'ramble', 21, 7, '20');
        await expect(page.locator('[data-testid="flash-success"]')).toContainText('Ramble 21-07 bet placed');

        expect(await readWalletBalance(page)).toBeCloseTo(before - 30, 2);
        await expect(page.locator('[data-testid="ld-my-bet"]')).toHaveCount(2);

        await page.click('[data-testid="ld-link-history"]');
        const rows = page.locator('[data-testid="ld-history-row"]');
        await expect(rows).toHaveCount(2);
        await expect(rows.first()).toContainText('Ramble');
        await expect(rows.first()).toContainText('Waiting for draw');
        await expect(rows.nth(1)).toContainText('Straight');
    });

    test('with "Test accounts only" on, only test accounts see and play 2D', async ({ page }) => {
        await markTestAccount(page, TESTER.mobile);
        await configureLiveDraw(page, { enabled: true, testUsersOnly: true, drawTime: '23:59', cutoff: '1' });

        // A real player: no home card, and the game page sends them home.
        await loginAs(page, USER.mobile, USER.password);
        await page.goto(`${BASE_URL}/`);
        await expect(page.locator('[data-testid="wallet-bar"]')).toBeVisible();
        await expect(page.locator('[data-testid="play-2d-card"]')).toHaveCount(0);
        await page.goto(`${BASE_URL}/play/2d`);
        await expect(page).not.toHaveURL(/\/play\/2d/);

        // A test account: sees the banner card and can bet.
        await loginAs(page, TESTER.mobile, TESTER.password);
        await page.goto(`${BASE_URL}/`);
        await expect(page.locator('[data-testid="play-2d-card"] img')).toHaveAttribute('alt', '2D Lotto Live Draw');
        await place2dBet(page, 'straight', 3, 4, '5');
        await expect(page.locator('[data-testid="flash-success"]')).toContainText('Straight 03-04 bet placed');

        await configureLiveDraw(page, { testUsersOnly: false });
    });

    test('agent accounts cannot bet on 2D, even by posting the form directly', async ({ page }) => {
        await configureLiveDraw(page, { enabled: true, testUsersOnly: false, drawTime: '23:59', cutoff: '1' });
        await loginAs(page, SUB_AGENT.mobile, SUB_AGENT.password);

        await page.goto(`${BASE_URL}/play/2d`);
        await expect(page.locator('[data-testid="ld-play-blocked"]')).toContainText('Betting not available');
        await expect(page.locator('[data-testid="ld-bet-form"]')).toHaveCount(0);

        // A hand-made POST is refused by the server too.
        const res = await page.request.post(`${BASE_URL}/play/2d/bet`, {
            form: { _token: 'x', bet_type: 'straight', number1: '1', number2: '2', amount: '10' },
            maxRedirects: 0,
        });
        expect([302, 403]).toContain(res.status());
        await page.goto(`${BASE_URL}/play/2d`);
        await expect(page.locator('[data-testid="ld-my-bet"]')).toHaveCount(0);
    });

    test('a combination that reaches its total bet limit is sold out and cannot be picked', async ({ page }) => {
        // ₱15 per combination (min bet ₱5). 11-12 and 12-11 are one combination, Straight + Ramble together.
        await configureLiveDraw(page, { enabled: true, testUsersOnly: false, drawTime: '23:59', cutoff: '1', comboLimit: '15' });
        await loginAs(page, USER.mobile, USER.password);

        await page.goto(`${BASE_URL}/play/2d`);
        await page.click('[data-testid="ld-num-11"]');
        await page.click('[data-testid="ld-num-12"]');
        await expect(page.locator('[data-testid="ld-combo-left"]')).toHaveText('₱15.00 left on 11-12 for this draw');
        await page.fill('[data-testid="ld-amount"]', '10');
        await page.click('[data-testid="ld-btn-place-bet"]');
        await expect(page.locator('[data-testid="flash-success"]')).toContainText('Straight 11-12 bet placed');

        // Ramble 12-11: ₱5 left, so ₱10 can't be placed - ₱5 can.
        await page.click('[data-testid="ld-type-ramble"]');
        await page.click('[data-testid="ld-num-12"]');
        await page.click('[data-testid="ld-num-11"]');
        await expect(page.locator('[data-testid="ld-combo-left"]')).toHaveText('₱5.00 left on 11-12 for this draw');
        await page.fill('[data-testid="ld-amount"]', '10');
        await expect(page.locator('[data-testid="ld-btn-place-bet"]')).toBeDisabled();
        await page.fill('[data-testid="ld-amount"]', '5');
        await page.click('[data-testid="ld-btn-place-bet"]');
        await expect(page.locator('[data-testid="flash-success"]')).toContainText('Ramble 12-11 bet placed');

        // Now sold out: with 11 picked, 12 is greyed and can't be picked (and the other way round).
        await page.goto(`${BASE_URL}/play/2d`);
        await page.click('[data-testid="ld-num-11"]');
        await expect(page.locator('[data-testid="ld-num-12"]')).toHaveClass(/is-sold-out/);
        await expect(page.locator('[data-testid="ld-num-12"]')).toBeDisabled();
        await expect(page.locator('[data-testid="ld-num-13"]')).toBeEnabled();
        await page.goto(`${BASE_URL}/play/2d`);
        await page.click('[data-testid="ld-num-12"]');
        await expect(page.locator('[data-testid="ld-num-11"]')).toBeDisabled();

        // Forcing it past the page is refused by the server.
        await page.goto(`${BASE_URL}/play/2d`);
        await page.click('[data-testid="ld-num-11"]');
        await page.locator('[data-testid="ld-num-12"]').evaluate((b: HTMLButtonElement) => { b.disabled = false; b.classList.remove('is-sold-out'); });
        await page.click('[data-testid="ld-num-12"]');
        await page.locator('[data-testid="ld-btn-place-bet"]').evaluate((b: HTMLButtonElement) => { b.disabled = false; });
        await page.locator('[data-testid="ld-amount"]').evaluate((i: HTMLInputElement) => { i.removeAttribute('max'); i.value = '5'; });
        await page.click('[data-testid="ld-btn-place-bet"]');
        await expect(page.locator('[data-testid="flash-error"]')).toContainText('11-12 is sold out for this draw.');

        // Another combination still takes bets.
        await place2dBet(page, 'straight', 11, 13, '5');
        await expect(page.locator('[data-testid="flash-success"]')).toContainText('Straight 11-13 bet placed');

        await configureLiveDraw(page, { comboLimit: '300' });
    });

    test('a player who reaches their own bet limit on a combination sees it sold out', async ({ page }) => {
        // ₱15 per player per combination, ₱300 from everyone: the player's own limit bites first.
        await configureLiveDraw(page, { enabled: true, testUsersOnly: false, drawTime: '23:59', cutoff: '1', comboLimit: '300', playerComboLimit: '15' });
        await loginAs(page, USER.mobile, USER.password);

        await page.goto(`${BASE_URL}/play/2d`);
        await page.click('[data-testid="ld-num-25"]');
        await page.click('[data-testid="ld-num-26"]');
        await expect(page.locator('[data-testid="ld-combo-left"]')).toHaveText('₱15.00 left on 25-26 for this draw');
        await page.fill('[data-testid="ld-amount"]', '10');
        await page.click('[data-testid="ld-btn-place-bet"]');
        await expect(page.locator('[data-testid="flash-success"]')).toContainText('Straight 25-26 bet placed');

        // Ramble 26-25 is the same combination: ₱5 left, so only ₱5 fits.
        await page.click('[data-testid="ld-type-ramble"]');
        await page.click('[data-testid="ld-num-26"]');
        await page.click('[data-testid="ld-num-25"]');
        await expect(page.locator('[data-testid="ld-combo-left"]')).toHaveText('₱5.00 left on 25-26 for this draw');
        await page.fill('[data-testid="ld-amount"]', '10');
        await expect(page.locator('[data-testid="ld-btn-place-bet"]')).toBeDisabled();
        await page.fill('[data-testid="ld-amount"]', '5');
        await page.click('[data-testid="ld-btn-place-bet"]');
        await expect(page.locator('[data-testid="flash-success"]')).toContainText('Ramble 26-25 bet placed');

        // Their limit is used up on 25-26 only: 26 is greyed next to 25, but 27 is open.
        await page.goto(`${BASE_URL}/play/2d`);
        await page.click('[data-testid="ld-num-25"]');
        await expect(page.locator('[data-testid="ld-num-26"]')).toHaveClass(/is-sold-out/);
        await expect(page.locator('[data-testid="ld-num-26"]')).toBeDisabled();
        await expect(page.locator('[data-testid="ld-num-27"]')).toBeEnabled();

        // Forcing it past the page is refused by the server.
        await page.goto(`${BASE_URL}/play/2d`);
        await page.click('[data-testid="ld-num-25"]');
        await page.locator('[data-testid="ld-num-26"]').evaluate((b: HTMLButtonElement) => { b.disabled = false; b.classList.remove('is-sold-out'); });
        await page.click('[data-testid="ld-num-26"]');
        await page.locator('[data-testid="ld-btn-place-bet"]').evaluate((b: HTMLButtonElement) => { b.disabled = false; });
        await page.locator('[data-testid="ld-amount"]').evaluate((i: HTMLInputElement) => { i.removeAttribute('max'); i.value = '5'; });
        await page.click('[data-testid="ld-btn-place-bet"]');
        await expect(page.locator('[data-testid="flash-error"]')).toContainText('25-26 is sold out for this draw.');

        // A different combination is still open to the same player.
        await place2dBet(page, 'straight', 25, 27, '5');
        await expect(page.locator('[data-testid="flash-success"]')).toContainText('Straight 25-27 bet placed');

        await configureLiveDraw(page, { playerComboLimit: '50' });
    });

    test('bets outside the limits are refused', async ({ page }) => {
        // Room per combination must not be the reason the page blocks it: leave the
        // player limit above the max bet so only the server-side max-bet check applies.
        await configureLiveDraw(page, { enabled: true, drawTime: '23:59', cutoff: '1', playerComboLimit: '100' });
        await loginAs(page, USER.mobile, USER.password);

        // Bypass the browser's min/max - the server must refuse it too.
        await page.goto(`${BASE_URL}/play/2d`);
        await page.click('[data-testid="ld-num-1"]');
        await page.click('[data-testid="ld-num-2"]');
        await page.fill('[data-testid="ld-amount"]', '51');
        // The page caps the field at ₱50 after every change - lift it right before submitting.
        await page.locator('[data-testid="ld-amount"]').evaluate((el: HTMLInputElement) => { el.removeAttribute('max'); });
        await page.click('[data-testid="ld-btn-place-bet"]');
        await expect(page.locator('[data-testid="flash-error"]')).toContainText('Bet amount must be from ₱5.00 to ₱50.00.');

        await configureLiveDraw(page, { playerComboLimit: '50' });
    });

    test('betting closes at the cutoff until midnight', async ({ page }) => {
        // Draw 10 minutes from now with a 30-minute cutoff: already past the cutoff.
        await configureLiveDraw(page, { enabled: true, drawTime: manila(10).time, cutoff: '30' });
        test.skip(manila(10).date !== manila(0).date, 'Too close to midnight');

        await loginAs(page, USER.mobile, USER.password);
        await page.goto(`${BASE_URL}/play/2d`);

        await expect(page.locator('[data-testid="ld-betting-closed"]')).toContainText('Betting closed');
        await expect(page.locator('[data-testid="ld-betting-closed"]')).toContainText('Betting opens again after midnight');
        await expect(page.locator('[data-testid="ld-bet-form"]')).toHaveCount(0);
    });
});
