// #region LoginE2E [C:3] [TYPE Test] [SEMANTICS e2e, login, auth, ui]
// @BRIEF E2E tests for login/logout flow.
// @RELATION BINDS_TO -> [LoginPage]
// @UX_STATE LoginForm -> Form rendered with username, password fields, submit button.
// @UX_STATE Authenticated -> Redirect to dashboards with sidebar visible.
// @UX_STATE InvalidCredentials -> Error toast or message shown.

import { test, expect } from '../fixtures/auth.fixture.js';

const FRONTEND_URL = process.env.FRONTEND_URL || 'http://127.0.0.1:8102';

test.describe('Login Flow', () => {
	test('should display login form with required fields', async ({ page }) => {
		await page.goto(`${FRONTEND_URL}/login`);

		// Form elements visible
		await expect(page.getByRole('heading', { name: /Вход|Login/ })).toBeVisible();
		await expect(page.getByLabel(/Имя пользователя|Username/)).toBeVisible();
		await expect(page.getByLabel(/Пароль|Password/)).toBeVisible();
		await expect(page.getByRole('button', { name: /Вход|Login/ })).toBeVisible();
	});

	test('should login with valid credentials and redirect', async ({ page }) => {
		await page.goto(`${FRONTEND_URL}/login`);

		await page.getByLabel(/Имя пользователя|Username/).fill('admin');
		await page.getByLabel(/Пароль|Password/).fill('admin123');
		await page.getByRole('button', { name: /Вход|Login/ }).click();

		// Should redirect away from /login
		await page.waitForURL(/\/(?!login)/, { timeout: 15_000 });
		// Sidebar navigation should be visible
		await expect(page.locator('nav')).toBeVisible();
		// User menu should exist
		await expect(page.getByRole('button', { name: /Меню пользователя|User/ })).toBeVisible();
	});

	test('should show error on invalid credentials', async ({ page }) => {
		await page.goto(`${FRONTEND_URL}/login`);

		await page.getByLabel(/Имя пользователя|Username/).fill('wrong');
		await page.getByLabel(/Пароль|Password/).fill('wrong');
		await page.getByRole('button', { name: /Вход|Login/ }).click();

		// Should stay on login page with error feedback
		await expect(page.getByRole('heading', { name: /Вход|Login/ })).toBeVisible({ timeout: 10_000 });
		// Check for error toast or message
		const errorVisible = await page.getByText(/ошиб|error|invalid|401|Unauthorized/i).first().isVisible().catch(() => false);
		expect(errorVisible).toBeTruthy();
	});
});
// #endregion LoginE2E
