import { test as base, type Page } from "@playwright/test"

import { registerTestUser, type TestUser } from "#tests/e2e/support/auth-api"

interface RealLoginPage {
	page: Page
	user: TestUser
	login(password?: string): Promise<void>
	submitWithEnter(password?: string): Promise<void>
	getCookie(name: string): Promise<string | undefined>
}

export const test = base.extend<{ realLoginPage: RealLoginPage }>({
	realLoginPage: async ({ page }, use) => {
		const user = await registerTestUser()

		await page.goto("/login")
		await page.getByRole("heading", { name: "Вход" }).waitFor()

		const realLoginPage: RealLoginPage = {
			page,
			user,

			async login(password = user.password) {
				await page.getByRole("textbox", { name: "Логин" }).fill(user.username)
				await page.getByLabel("Пароль").fill(password)
				await page.getByRole("button", { name: "Войти" }).click()
			},

			async submitWithEnter(password = user.password) {
				await page.getByRole("textbox", { name: "Логин" }).fill(user.username)
				await page.getByLabel("Пароль").fill(password)
				await page.getByLabel("Пароль").press("Enter")
			},

			async getCookie(name: string) {
				const cookies = await page.context().cookies()
				return cookies.find((cookie) => cookie.name === name)?.value
			},
		}

		await use(realLoginPage)
	},
})

export { expect } from "@playwright/test"
