import { test, expect } from '@playwright/test';
import { BASE_URL, ADMIN, 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('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, ADMIN.mobile, ADMIN.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');
    });

});
