import { test, expect } from '@playwright/test';
import { BASE_URL, AUDITOR, FINANCE, loginAs, registerAndLogin, ensureMinesEnabled, playMinesRound } from '../helpers';

test.describe('WFBO Recent Bets', () => {

    test.beforeEach(async ({ page }) => {
        await loginAs(page, FINANCE.mobile, FINANCE.password);
    });

    test('recent bets page loads with the bets table', async ({ page }) => {
        await page.goto(`${BASE_URL}/wfbo/recent-bets`);
        await expect(page.locator('[data-testid="recent-bets-table"]')).toBeVisible();
    });

    test('recent-bets count API returns a numeric total', async ({ page }) => {
        await page.goto(`${BASE_URL}/wfbo/recent-bets`);
        const response = await page.request.get(`${BASE_URL}/wfbo/recent-bets/count`);
        expect(response.status()).toBe(200);
        const data = await response.json();
        expect(typeof data.total).toBe('number');
    });

    test('date filter narrows the feed and retains its values; Clear resets it', async ({ page }) => {
        await page.goto(`${BASE_URL}/wfbo/recent-bets`);
        const unfilteredTotal = await page.locator('[data-testid="recent-bets-total"]').textContent();

        // A range far in the past -> no bets.
        await page.goto(`${BASE_URL}/wfbo/recent-bets?date_from=2000-01-01&date_to=2000-01-02`);
        await expect(page.locator('[data-testid="recent-bets-total"]')).toHaveText('0 bets');
        await expect(page.locator('[data-testid="recent-bets-table"]')).toContainText('No bets yet.');
        await expect(page.locator('[data-testid="input-recent-bets-date-from"]')).toHaveValue('2000-01-01');
        await expect(page.locator('[data-testid="input-recent-bets-date-to"]')).toHaveValue('2000-01-02');

        // Clear returns to the full feed.
        await page.click('[data-testid="link-recent-bets-clear"]');
        await expect(page).toHaveURL(`${BASE_URL}/wfbo/recent-bets`);
        await expect(page.locator('[data-testid="recent-bets-total"]')).toHaveText(unfilteredTotal ?? '');
        await expect(page.locator('[data-testid="link-recent-bets-clear"]')).toHaveCount(0);
    });

    test('Live Racing filter narrows the feed to Live Racing bets only', async ({ page }) => {
        await page.goto(`${BASE_URL}/wfbo/recent-bets`);
        await page.click('[data-testid="filter-live-racing"]');
        await page.waitForLoadState('networkidle');

        expect(page.url()).toContain('category=live_racing');
        await expect(page.locator('[data-testid="filter-live-racing"]')).toHaveClass(/is-active/);

        const table = page.locator('[data-testid="recent-bets-table"]');
        await expect(table).toBeVisible();
        const hasRows = !(await table.textContent())?.includes('No bets yet.');
        if (hasRows) {
            await expect(table).toContainText('Live Racing');
            await expect(table).not.toContainText('Mines');
            await expect(table).not.toContainText('Video Karera');
        }
    });

    test('Mini Games filter narrows the feed to non-Live-Racing bets only', async ({ page }) => {
        await page.goto(`${BASE_URL}/wfbo/recent-bets`);
        await page.click('[data-testid="filter-mini-games"]');
        await page.waitForLoadState('networkidle');

        expect(page.url()).toContain('category=mini_games');
        await expect(page.locator('[data-testid="filter-mini-games"]')).toHaveClass(/is-active/);

        const table = page.locator('[data-testid="recent-bets-table"]');
        await expect(table).toBeVisible();
        const hasRows = !(await table.textContent())?.includes('No bets yet.');
        if (hasRows) {
            await expect(table).not.toContainText('Live Racing');
        }

        // "All" returns the unfiltered feed.
        await page.click('[data-testid="filter-all"]');
        await page.waitForLoadState('networkidle');
        expect(page.url()).not.toContain('category=');
        await expect(page.locator('[data-testid="filter-all"]')).toHaveClass(/is-active/);
    });

    test('a completed Mines round appears in the recent bets feed', async ({ page }) => {
        await ensureMinesEnabled(page); // ends logged in as ADMIN

        const { mobile, password } = await registerAndLogin(page); // ends logged in as the fresh player

        // Credit the fresh player's wallet so they can afford the minimum Mines bet.
        await loginAs(page, AUDITOR.mobile, AUDITOR.password);
        await page.goto(`${BASE_URL}/wfbo/users?search=${encodeURIComponent(mobile)}`);
        const userRow = page.locator('[data-testid^="user-row-"]').first();
        await expect(userRow).toBeVisible();
        const userId = (await userRow.getAttribute('data-testid'))?.replace('user-row-', '');
        await page.goto(`${BASE_URL}/wfbo/users/${userId}/transactions`);
        await page.fill('[data-testid="adj-amount"]', '100');
        await page.fill('[data-testid="adj-reason"]', 'Acceptance test funding for Mines round');
        await page.click('[data-testid="adj-submit"]');
        await expect(page.locator('[data-testid="flash-success"]')).toBeVisible();

        await loginAs(page, mobile, password);
        const played = await playMinesRound(page);
        expect(played).toBeTruthy();

        await loginAs(page, FINANCE.mobile, FINANCE.password);
        await page.goto(`${BASE_URL}/wfbo/recent-bets`);
        await expect(page.locator('[data-testid="recent-bets-table"]')).toContainText('Mines');
    });

});
