import { test, expect } from '@playwright/test';
import { BASE_URL, AUDITOR, FINANCE, loginAs, registerAndLogin, adjustWalletAsAuditor, manila } from '../helpers';
import { readFileSync } from 'node:fs';

// Finance ▸ Daily Audit: pick a day, generate its PDF, and download it (or any earlier one) from the list.
test.describe('WFBO Finance ▸ Daily Audit', () => {
    test.setTimeout(120_000);

    test('an auditor generates a day\'s report and downloads it from the list', async ({ page }, testInfo) => {
        const today = manila().date;

        // Something to report: a new player credited by an auditor today.
        const player = await registerAndLogin(page);
        await adjustWalletAsAuditor(page, player.mobile, '300', 'Daily audit e2e');

        await page.goto(`${BASE_URL}/wfbo/deposits`);
        await page.click('[data-testid="wfbo-nav-daily-audit"]');
        await expect(page).toHaveURL(`${BASE_URL}/wfbo/audit`);
        // The page is just the generator and the list - no on-screen report.
        await expect(page.locator('[data-testid="da-generate-form"]')).toBeVisible();
        await expect(page.locator('[data-testid="da-date"]')).toHaveAttribute('max', today);
        const before = await page.locator('[data-testid="da-reports"] tbody tr').count();

        await page.fill('[data-testid="da-date"]', today);
        await page.click('[data-testid="da-generate"]');
        await expect(page.locator('[data-testid="flash-success"]')).toContainText('is ready to download');

        // Newest first: the report just generated heads the list.
        const list = page.locator('[data-testid="da-reports"] tbody tr');
        await expect(list).toHaveCount(before + 1);
        const newest = list.first();
        const [y, m, d] = today.split('-').map(Number);
        const dayLabel = new Intl.DateTimeFormat('en-US', { weekday: 'short', month: 'short', day: 'numeric', year: 'numeric', timeZone: 'UTC' })
            .format(new Date(Date.UTC(y, m - 1, d)));
        await expect(newest.locator('[data-testid="da-report-day"]')).toHaveText(dayLabel);
        await expect(newest.locator('[data-testid="da-report-lr"]')).toBeVisible();
        // Headline money per report: Cash on Hand and Net Revenue (no separate GGR column).
        await expect(newest.locator('[data-testid="da-report-cash-on-hand"]')).toHaveText(/^₱-?[\d,]+\.\d{2}$/);
        await expect(newest.locator('[data-testid="da-report-net-revenue"]')).toHaveText(/^₱-?[\d,]+\.\d{2}$/);
        await expect(page.locator('[data-testid="da-reports"] thead')).not.toContainText('GGR');
        await expect(newest).toContainText('Auditor User');
        await page.screenshot({ path: testInfo.outputPath('daily-audit-list.png'), fullPage: true });

        const [download] = await Promise.all([
            page.waitForEvent('download'),
            newest.locator('[data-testid^="da-download-"]').click(),
        ]);
        expect(download.suggestedFilename()).toMatch(new RegExp(`^daily-audit-${today.replaceAll('-', '')}-generated-\\d{8}-\\d{6}\\.pdf$`));
        const path = testInfo.outputPath('daily-audit.pdf');
        await download.saveAs(path);
        expect(readFileSync(path).subarray(0, 4).toString()).toBe('%PDF');
    });

    test('a day in the future is refused', async ({ page }) => {
        await loginAs(page, AUDITOR.mobile, AUDITOR.password);
        await page.goto(`${BASE_URL}/wfbo/audit`);
        const tomorrow = manila(24 * 60).date;
        // Past the date picker's max - the server refuses it too.
        await page.locator('[data-testid="da-date"]').evaluate((el: HTMLInputElement, d: string) => { el.removeAttribute('max'); el.value = d; }, tomorrow);
        await page.click('[data-testid="da-generate"]');
        await expect(page.locator('[data-testid="flash-error"]')).toHaveText('Pick a valid day, today or earlier.');
    });

    test('finance staff without the auditor role can\'t open it', async ({ page }) => {
        await loginAs(page, FINANCE.mobile, FINANCE.password);
        await page.goto(`${BASE_URL}/wfbo/deposits`);
        await expect(page.locator('[data-testid="wfbo-nav-deposits"]')).toBeVisible();
        await expect(page.locator('[data-testid="wfbo-nav-daily-audit"]')).toHaveCount(0);
        const response = await page.goto(`${BASE_URL}/wfbo/audit`);
        expect(response?.status()).toBe(403);
    });
});
