import { test, expect } from "#tests/e2e/fixtures/real-auth"

test.describe("Login (Integration)", () => {
	test("should login with registered credentials and stay authenticated after reload", async ({
		realLoginPage,
	}) => {
		const { page, user } = realLoginPage

		await realLoginPage.login()

		await expect(page).toHaveURL("/")
		await expect(
			page.getByRole("heading", {
				name: new RegExp(`Добро пожаловать, ${user.firstName}`),
			}),
		).toBeVisible()
		await expect
			.poll(() => realLoginPage.getCookie("access_token"))
			.toBeTruthy()
		await expect
			.poll(() => realLoginPage.getCookie("refresh_token"))
			.toBeTruthy()

		await page.reload()

		await expect(page).toHaveURL("/")
		await expect(
			page.getByRole("heading", {
				name: new RegExp(`Добро пожаловать, ${user.firstName}`),
			}),
		).toBeVisible()
	})

	test("should keep user on login page and avoid auth cookies for invalid password", async ({
		realLoginPage,
	}) => {
		const { page, user } = realLoginPage
		const wrongPassword = `${user.password}_wrong`

		await realLoginPage.login(wrongPassword)

		await expect(page).toHaveURL(/\/login$/)
		await expect(page.getByRole("button", { name: "Войти" })).toBeEnabled()
		await expect(page.getByRole("textbox", { name: "Логин" })).toHaveValue(
			user.username,
		)
		await expect(page.getByLabel("Пароль")).toHaveValue(wrongPassword)
		await expect
			.poll(() => realLoginPage.getCookie("access_token"))
			.toBeFalsy()
		await expect
			.poll(() => realLoginPage.getCookie("refresh_token"))
			.toBeFalsy()
	})

	test("should submit the login form with Enter from password field", async ({
		realLoginPage,
	}) => {
		const { page, user } = realLoginPage

		await realLoginPage.submitWithEnter()

		await expect(page).toHaveURL("/")
		await expect(
			page.getByRole("heading", {
				name: new RegExp(`Добро пожаловать, ${user.firstName}`),
			}),
		).toBeVisible()
	})
})
