import { test as setup, expect } from '@playwright/test';

const authFile = 'tests/e2e/.auth/user.json';

const baseUrl = 'https://pp-planer.ddev.site';

setup('authenticate', async ({ page }) => {
    // Navigate to login page to establish session cookies (incl. XSRF-TOKEN)
    await page.goto(`${baseUrl}/login`);

    // Get XSRF token from cookies for CSRF protection
    const cookies = await page.context().cookies(baseUrl);
    const xsrfCookie = cookies.find((c) => c.name === 'XSRF-TOKEN');
    const xsrfToken = decodeURIComponent(xsrfCookie?.value || '');

    // POST to dev-login route directly (bypasses Vue rendering dependency)
    await page.request.post(`${baseUrl}/dev-login`, {
        headers: {
            'X-XSRF-TOKEN': xsrfToken,
        },
    });

    // Navigate to dashboard to confirm login and load session
    await page.goto(`${baseUrl}/dashboard`);
    await page.waitForURL('**/dashboard');

    // Save signed-in state
    await page.context().storageState({ path: authFile });
});
