import { test, expect, type Page } from '@playwright/test';
import { BASE_URL, ADMIN, USER, loginAs } from '../helpers';

/**
 * Enables/disables Royale King 999 through the WFBO settings page (idempotent).
 * Leaves the browser logged in as ADMIN.
 */
async function configureLuckyNine(page: Page, opts: { enabled: boolean; houseWinRate?: string }): Promise<void> {
    await loginAs(page, ADMIN.mobile, ADMIN.password);
    await page.goto(`${BASE_URL}/wfbo/lucky-999/settings`, { waitUntil: 'domcontentloaded' });

    const toggle   = page.locator('[data-testid="toggle-l9-enabled"]');
    const hwrInput = page.locator('[data-testid="input-l9-house-win-rate"]');
    let changed    = false;

    if (opts.enabled && !(await toggle.isChecked())) {
        await toggle.check();
        changed = true;
    } else if (!opts.enabled && (await toggle.isChecked())) {
        await toggle.uncheck();
        changed = true;
    }

    if (opts.houseWinRate !== undefined && (await hwrInput.inputValue()) !== opts.houseWinRate) {
        await hwrInput.fill(opts.houseWinRate);
        changed = true;
    }

    if (changed) {
        await page.click('[data-testid="btn-save-l9-settings"]');
        await expect(page.locator('[data-testid="flash-success"]')).toBeVisible();
    }
}

test.describe.serial('Royale King 999 — Game Page', () => {

    test.afterAll(async ({ browser }) => {
        // Restore the shipped defaults so other specs are unaffected.
        const page = await browser.newPage();
        await configureLuckyNine(page, { enabled: false, houseWinRate: '' });
        await page.close();
    });

    test('game page loads at /play/lucky-999 with the reels and controls', async ({ page }) => {
        await configureLuckyNine(page, { enabled: true, houseWinRate: '' });
        await loginAs(page, USER.mobile, USER.password);

        await page.goto(`${BASE_URL}/play/lucky-999`, { waitUntil: 'domcontentloaded' });

        await expect(page.locator('[data-testid="lucky999-page"]')).toBeVisible();
        await expect(page.locator('#lbTitle')).toHaveText('ROYALE KING 999');
        await expect(page).toHaveTitle(/Royale King 999/);
        await expect(page.locator('[data-testid="lucky999-spin"]')).toBeVisible();
        await expect(page.locator('[data-testid="lucky999-balance"]')).toBeVisible();
        await expect(page.locator('[data-testid="lucky999-bet-chip"]').first()).toBeVisible();
    });

    test('GET /play/lucky-999/state returns wallet balance, chips and bet limit', async ({ page }) => {
        await configureLuckyNine(page, { enabled: true, houseWinRate: '' });
        await loginAs(page, USER.mobile, USER.password);

        const response = await page.request.get(`${BASE_URL}/play/lucky-999/state`);
        expect(response.status()).toBe(200);
        const body = await response.json();
        expect(body).toHaveProperty('walletBalance');
        expect(Array.isArray(body.chipValues)).toBe(true);
        expect(body.chipValues.length).toBeGreaterThan(0);
        expect(body).toHaveProperty('maxBetAmount');
    });

    test('a spin is settled by the server and debits the wallet', async ({ page }) => {
        // HWR 100 guarantees a LOSS, so the wallet movement is deterministic.
        await configureLuckyNine(page, { enabled: true, houseWinRate: '100' });
        await loginAs(page, USER.mobile, USER.password);

        const before = parseFloat(
            (await (await page.request.get(`${BASE_URL}/play/lucky-999/state`)).json()).walletBalance,
        );
        if (before < 5) {
            test.skip(true, 'Insufficient balance to place bet');
            return;
        }

        await page.goto(`${BASE_URL}/play/lucky-999`, { waitUntil: 'domcontentloaded' });
        await expect(page.locator('[data-testid="lucky999-page"]')).toBeVisible();
        // The spin button only enables once the state fetch has loaded a real balance.
        await expect(page.locator('[data-testid="lucky999-spin"]')).toBeEnabled();

        const [response] = await Promise.all([
            page.waitForResponse(r => r.url().includes('/play/lucky-999/spin') && r.request().method() === 'POST'),
            page.click('[data-testid="lucky999-spin"]'),
        ]);
        expect(response.status()).toBe(200);

        const body = await response.json();
        expect(body.success).toBe(true);
        expect(body.reels).toHaveLength(3);
        expect(body.outcome).toBe('lost');
        expect(parseFloat(body.payout)).toBe(0);
        // The default ₱5 chip was spent.
        expect(parseFloat(body.walletBalance)).toBeCloseTo(before - 5, 2);

        // The on-screen wallet reflects the stake immediately (deducted on spin,
        // not only once the reels settle).
        const expected = (before - 5).toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
        await expect(page.locator('[data-testid="lucky999-balance"]')).toContainText(expected);
    });

    test('the game redirects to home while disabled', async ({ page }) => {
        await configureLuckyNine(page, { enabled: false });
        await loginAs(page, USER.mobile, USER.password);

        await page.goto(`${BASE_URL}/play/lucky-999`, { waitUntil: 'domcontentloaded' });
        await expect(page).toHaveURL(`${BASE_URL}/`);
    });

    test('unauthenticated access redirects to /login', async ({ page }) => {
        await page.context().clearCookies();
        await page.goto(`${BASE_URL}/play/lucky-999`);
        expect(page.url()).toContain('/login');
    });
});
