import { test, expect, Page, TestInfo } from '@playwright/test';
import {
    BASE_URL, ADMIN, SUPER_ADMIN, AUDITOR, loginAs, registerUserWithReferralCode, walletAmount,
    createPaymentDetail, requestDeposit, approveNewestDepositOf, manila, windowAroundNow,
    disableAllBonusCampaigns, createBonusCampaign,
} from '../helpers';

// Bonus wallet: a separate player balance for mini games only. Bets take it
// first (then the main wallet), wins go to the main wallet, refunds go back
// where the stake came from, and it is never withdrawable. Each bonus source
// (first deposit bonus, deposit campaigns, cashback, claimable bonuses) can
// credit the main or the bonus wallet; the auditor can adjust either.

const AGENT_REFERRAL_CODE = 'ABCDEF01';

/** One first deposit bonus campaign running today (min ₱100), or none when value is omitted. */
async function configureFirstDepositBonus(page: Page, cfg: { value?: string; creditTo?: 'main' | 'bonus' }): Promise<void> {
    await disableAllBonusCampaigns(page, 'fdb');
    if (cfg.value !== undefined) {
        const campaign = await createBonusCampaign(page, 'fdb', { value: cfg.value, min: '100', creditTo: cfg.creditTo ?? 'main' });
        expect(campaign.id).toBeGreaterThan(0);
    }
}

/** Royale King 999 on/off; house win rate 100 makes every spin a loss (predictable balances). */
async function configureRoyaleKing(page: Page, enabled: boolean, houseWinRate: string): Promise<void> {
    await loginAs(page, ADMIN.mobile, ADMIN.password);
    await page.goto(`${BASE_URL}/wfbo/lucky-999/settings`, { waitUntil: 'domcontentloaded' });
    await page.locator('[data-testid="toggle-l9-enabled"]').setChecked(enabled);
    await page.fill('[data-testid="input-l9-house-win-rate"]', houseWinRate);
    await page.click('[data-testid="btn-save-l9-settings"]');
    await expect(page.locator('[data-testid="flash-success"]')).toBeVisible();
}

/** Player-view evidence: a named full-page screenshot in the test's output folder. */
async function snap(page: Page, testInfo: TestInfo, name: string): Promise<void> {
    const viewport = page.viewportSize();
    await page.setViewportSize({ width: 390, height: 844 });   // a player's phone
    await page.addStyleTag({ content: '.sf-toolbar, .sf-minitoolbar, .sf-toolbarreset { display: none !important; }' });
    await page.waitForTimeout(900);   // let balance count-ups and layout settle
    await page.screenshot({ path: testInfo.outputPath(`player-${name}.png`) });
    if (viewport) await page.setViewportSize(viewport);
}

async function openUserPage(page: Page, mobile: string): Promise<void> {
    await page.goto(`${BASE_URL}/wfbo/users?search=${encodeURIComponent(mobile)}`);
    const row  = page.locator('[data-testid^="user-row-"]').filter({ hasText: mobile });
    const href = await row.locator('[data-testid^="btn-view-transactions-"]').getAttribute('href');
    await page.goto(`${BASE_URL}${href ?? ''}`);
}

test.describe.serial('Bonus wallet', () => {
    test.setTimeout(240_000);

    test.beforeEach(async ({ page }) => {
        page.on('dialog', (d) => { d.accept().catch(() => {}); });
    });

    test.afterAll(async ({ browser }) => {
        const page = await browser.newPage();
        await configureFirstDepositBonus(page, {});
        await configureRoyaleKing(page, false, '');
        await page.close();
    });

    test('first deposit bonus to the bonus wallet is spent first on a mini game and is not withdrawable', async ({ page }, testInfo) => {
        await loginAs(page, ADMIN.mobile, ADMIN.password);
        const account = await createPaymentDetail(page, `BW Bank ${Date.now()}`);
        await configureFirstDepositBonus(page, { value: '50', creditTo: 'bonus' });
        await configureRoyaleKing(page, true, '100');

        // The offer says where the bonus goes.
        const player = await registerUserWithReferralCode(page, AGENT_REFERRAL_CODE);
        await expect(page.locator('[data-testid="wallet-bar-bonus"]')).toBeHidden();
        await page.goto(`${BASE_URL}/deposit`);
        await expect(page.locator('[data-testid="first-deposit-bonus-banner"]')).toContainText('Bonus Wallet');
        await snap(page, testInfo, '1-deposit-page-offer');

        await requestDeposit(page, account, '100');
        const toast = await approveNewestDepositOf(page, player.mobile);
        expect(toast).toContain('First deposit bonus ₱50.00 credited to the bonus wallet.');

        // Home wallet bar: ₱100 main + ₱50 bonus.
        await loginAs(page, player.mobile, player.password);
        await page.waitForTimeout(700);
        expect(walletAmount(await page.locator('[data-testid="wallet-bar-amount"]').textContent())).toBe(100);
        await expect(page.locator('[data-testid="wallet-bar-bonus-amount"]')).toHaveText('₱50.00');
        await snap(page, testInfo, '2-home-wallet-bar-bonus');

        // A ₱5 Royale King spin (a loss) comes out of the bonus wallet; main is untouched.
        await page.goto(`${BASE_URL}/play/lucky-999`, { waitUntil: 'domcontentloaded' });
        await expect(page.locator('[data-testid="lucky999-page"] [data-testid="wallet-bar-bonus-amount"]')).toHaveText('₱50.00');
        await page.locator('[data-testid="lucky999-bet-chip"]').first().click();
        await snap(page, testInfo, '3-royale-king-before-spin');
        const [spin] = await Promise.all([
            page.waitForResponse((r) => r.url().includes('/play/lucky-999/spin') && r.request().method() === 'POST'),
            page.click('[data-testid="lucky999-spin"]'),
        ]);
        const body = await spin.json();
        expect(body.outcome).toBe('lost');
        const stake = 50 - parseFloat(body.bonusBalance);
        expect(stake).toBeGreaterThan(0);
        expect(parseFloat(body.walletBalance)).toBe(100);
        // The chip updates on the bet itself, without a reload.
        await expect(page.locator('[data-testid="lucky999-page"] [data-testid="wallet-bar-bonus-amount"]')).toHaveText(`₱${(50 - stake).toFixed(2)}`);
        await expect(page.locator('[data-testid="lucky999-balance"]')).toContainText('100.00');
        await expect(page.locator('[data-testid="lucky999-spin"]')).not.toHaveText(/SPINNING/, { timeout: 15000 });
        await snap(page, testInfo, '4-royale-king-after-spin');

        // Back on home: the wallet bar shows the spent bonus.
        await page.goto(`${BASE_URL}/`);
        await expect(page.locator('[data-testid="wallet-bar-bonus-amount"]')).toHaveText(`₱${(50 - stake).toFixed(2)}`);
        await snap(page, testInfo, '5-home-after-spin');

        // Withdrawals only see the main wallet.
        await page.goto(`${BASE_URL}/withdrawal`);
        await expect(page.locator('[data-testid="available-balance"]')).toHaveText('₱100.00');
        await snap(page, testInfo, '6-withdrawal-main-only');

        // WFBO shows both balances, and the bet row is tagged as a bonus-wallet row.
        await loginAs(page, ADMIN.mobile, ADMIN.password);
        await openUserPage(page, player.mobile);
        await expect(page.locator('[data-testid="user-wallet-balance"]')).toContainText('₱100.00');
        await expect(page.locator('[data-testid="user-bonus-wallet-balance"]')).toContainText(`₱${(50 - stake).toFixed(2)}`);
        await page.goto(`${page.url().split('?')[0]}?type=wallet`);
        await expect(page.locator('[data-testid^="tx-bonus-wallet-"]').first()).toBeVisible();

        // The auditor tops up the bonus wallet only.
        await loginAs(page, AUDITOR.mobile, AUDITOR.password);
        await openUserPage(page, player.mobile);
        await page.fill('[data-testid="adj-amount"]', '10');
        await page.selectOption('[data-testid="adj-wallet"]', 'bonus');
        await page.fill('[data-testid="adj-reason"]', 'Bonus wallet top-up');
        await page.click('[data-testid="adj-submit"]');
        await expect(page.locator('[data-testid="flash-success"]').first()).toContainText('Bonus wallet credit of ₱10.00');
        await expect(page.locator('[data-testid="user-bonus-wallet-balance"]')).toContainText(`₱${(60 - stake).toFixed(2)}`);
        await expect(page.locator('[data-testid="user-wallet-balance"]')).toContainText('₱100.00');
    });

    test('deposit campaigns, cashback campaigns and claimable bonuses can credit the bonus wallet', async ({ page }) => {
        const today = manila().date;
        const win   = windowAroundNow();
        await loginAs(page, SUPER_ADMIN.mobile, SUPER_ADMIN.password);

        // Deposit campaign: create with "Bonus wallet", then disable it straight away.
        const name = `BW Promo ${Date.now()}`;
        await page.goto(`${BASE_URL}/wfbo/deposit-campaigns/new`);
        await page.fill('[data-testid="input-dc-name"]', name);
        await page.fill('[data-testid="input-dc-start-date"]', today);
        await page.fill('[data-testid="input-dc-end-date"]', today);
        await page.fill('[data-testid="input-dc-window-start"]', win.start);
        await page.fill('[data-testid="input-dc-window-end"]', win.end);
        await page.check('[data-testid="dc-credit-to-bonus"]');
        await page.click('[data-testid="btn-submit-deposit-campaign"]');
        await expect(page).toHaveURL(/\/wfbo\/deposit-campaigns$/);
        const row = page.locator('[data-testid^="deposit-campaign-row-"]', { hasText: name });
        const id  = ((await row.getAttribute('data-testid')) ?? '').replace('deposit-campaign-row-', '');
        await expect(page.locator(`[data-testid="deposit-campaign-bonus-wallet-${id}"]`)).toBeVisible();
        await page.click(`[data-testid="btn-toggle-deposit-campaign-${id}"]`);
        await page.goto(`${BASE_URL}/wfbo/deposit-campaigns/${id}/edit`);
        await expect(page.locator('[data-testid="dc-credit-to-bonus"]')).toBeChecked();

        // Cashback campaign form offers the same choice.
        await page.goto(`${BASE_URL}/wfbo/cashback-campaigns/new`);
        await expect(page.locator('[data-testid="cb-credit-to-main"]')).toBeChecked();
        await expect(page.locator('[data-testid="cb-credit-to-bonus"]')).toBeVisible();

        // Claimable bonus form too.
        await page.goto(`${BASE_URL}/wfbo/bonuses/new`);
        await expect(page.locator('[data-testid="bonus-credit-to-main"]')).toBeChecked();
        await expect(page.locator('[data-testid="bonus-credit-to-bonus"]')).toBeVisible();
    });
});
