import { test, expect } from '@playwright/test';
import { BASE_URL, ADMIN, FINANCE, OPERATIONS, loginAs } from '../helpers';

test.describe('WFBO Cashflow — FINANCE access', () => {

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

    test('cashflow page loads with stat cards', async ({ page }) => {
        await page.goto(`${BASE_URL}/wfbo/cashflow`);
        await expect(page.locator('[data-testid="stat-cash-in"]')).toBeVisible();
        await expect(page.locator('[data-testid="stat-cash-out"]')).toBeVisible();
        await expect(page.locator('[data-testid="stat-net-period"]')).toBeVisible();
        await expect(page.locator('[data-testid="stat-cash-on-hand"]')).toBeVisible();
    });

    test('cash on hand card is scoped to the selected period, not all-time', async ({ page }) => {
        await page.goto(`${BASE_URL}/wfbo/cashflow`);
        const periodLabel = page.locator('[data-testid="stat-cash-on-hand"] .stat-sub').first();
        await expect(periodLabel).toHaveText(/^(January|February|March|April|May|June|July|August|September|October|November|December) \d{4}$/);
        await expect(page.locator('[data-testid="stat-cash-on-hand"]')).not.toContainText('All-time');
    });

    test('export PDF button is present', async ({ page }) => {
        await page.goto(`${BASE_URL}/wfbo/cashflow`);
        await expect(page.locator('[data-testid="btn-export-pdf"]')).toBeVisible();
    });

    test('period filter buttons are present', async ({ page }) => {
        await page.goto(`${BASE_URL}/wfbo/cashflow`);
        await expect(page.locator('[data-testid="period-this_month"]').first()).toBeVisible();
    });

});

test.describe('WFBO Cashflow — role guard', () => {

    test('ADMIN user can access cashflow (inherits ROLE_FINANCE via role hierarchy)', async ({ page }) => {
        await loginAs(page, ADMIN.mobile, ADMIN.password);
        await page.goto(`${BASE_URL}/wfbo/cashflow`);
        await expect(page.locator('[data-testid="stat-cash-in"]')).toBeVisible();
    });

    test('OPERATIONS user is blocked from cashflow', async ({ page }) => {
        await loginAs(page, OPERATIONS.mobile, OPERATIONS.password);
        await page.goto(`${BASE_URL}/wfbo/cashflow`);
        await expect(page.locator('[data-testid="stat-cash-in"]')).not.toBeVisible();
    });

});

test.describe('WFBO Cashflow Export', () => {

    test('export endpoint returns PDF content-type', async ({ page }) => {
        await loginAs(page, FINANCE.mobile, FINANCE.password);
        // Navigate first to establish session, then request via page.request
        await page.goto(`${BASE_URL}/wfbo/cashflow`);
        const response = await page.request.get(`${BASE_URL}/wfbo/cashflow/export`);
        expect(response.status()).toBe(200);
        const contentType = response.headers()['content-type'] ?? '';
        expect(contentType).toContain('pdf');
    });

});
