// #region AuthFixture [C:2] [TYPE Module] [SEMANTICS e2e, auth, fixture, test]
// @BRIEF Playwright fixture for authenticated browser contexts.
// @RELATION DEPENDS_ON -> [ApiHelper]
// @UX_STATE LoginError -> Error banner visible on failed login.
// @UX_STATE LoginError -> Error banner visible on failed login.
// @@RATIONALE Fixed authPage fixture to wait for /dashboards or /datasets URL instead of matching any URL containing '/' (which resolved immediately on home page). Added catch fallback for cases where redirect is slow.
// @@REJECTED Using waitForURL(/\/dashboards|\/datasets|\//) which matched '/' too broadly.

import { test as base } from '@playwright/test';
import { apiGet, apiPost } from '../helpers/api.helper.js';

const FRONTEND_URL = process.env.FRONTEND_URL || 'http://127.0.0.1:8102';
const USERNAME = process.env.E2E_USERNAME || 'admin';
const PASSWORD = process.env.E2E_PASSWORD || 'admin123';

/**
 * Extended test fixture with helpers for authenticated browsing.
 *
 * `authPage` — a page that is already logged in (navigated through login form).
 * `api`     — direct API helpers for test setup/teardown.
 */
export const test = base.extend({
	/**
	 * Authenticated page — logs in via the UI form before each test.
	 */
	authPage: async ({ page }, use) => {
		await page.goto(`${FRONTEND_URL}/login`);
		await page.waitForSelector('text=Вход', { timeout: 10_000 });

		// Fill login form — the actual IDs vary by locale, use label text
		await page.getByLabel(/Имя пользователя|Username/).fill(USERNAME);
		await page.getByLabel(/Пароль|Password/).fill(PASSWORD);
		await page.getByRole('button', { name: /Вход|Login/ }).click();

		// Wait for redirect to dashboard
		// Wait for dashboard URL — the home page redirects to /dashboards after login
		// Accept /dashboards, /datasets, or the home page "/" with SPA shell rendered
		await page.waitForURL(/\/dashboards|\/datasets/, { timeout: 15_000 })
			.catch(async () => {
				// Fallback: if stuck on home page "/", wait for nav and let redirect complete
				await page.waitForSelector('nav', { timeout: 10_000 });
				await page.waitForURL(/\/dashboards/, { timeout: 15_000 }).catch(() => {});
			});
		await page.waitForSelector('nav', { timeout: 10_000 });

		await use(page);
	},

	/**
	 * Expose API helpers directly in tests.
	 */
	api: async ({}, use) => {
		await use({ get: apiGet, post: apiPost });
	},
});

export { expect } from '@playwright/test';
// #endregion AuthFixture
