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

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

interface RealProjectsPage {
	page: Page
	modal: Locator
	user: TestUser
	openCreateModal(): Promise<void>
	/** Delete a project by ID via API (for cleanup) */
	deleteProject(projectId: string): Promise<void>
	/** Get all projects for the test user via API */
	getProjects(): Promise<{ id: string; name: string }[]>
}

export const test = base.extend<{ realProjectsPage: RealProjectsPage }>({
	realProjectsPage: async ({ page }, use) => {
		// Register a fresh user for each test
		const user = await registerTestUser()

		// Set auth cookies
		await page.context().addCookies([
			{
				name: "access_token",
				value: user.accessToken,
				domain: "localhost",
				path: "/",
			},
			{
				name: "refresh_token",
				value: user.refreshToken,
				domain: "localhost",
				path: "/",
			},
		])

		await page.goto("/projects")
		await page.getByRole("heading", { name: "Мои проекты" }).waitFor()

		const modal = page.locator("[role=dialog]")

		const realProjectsPage: RealProjectsPage = {
			page,
			modal,
			user,

			async openCreateModal() {
				await page.getByRole("button", { name: /Создать проект/ }).click()
				await modal.waitFor({ state: "visible" })
			},

			async deleteProject(projectId: string) {
				const res = await fetch(`${E2E_API_URL}/api/projects/${projectId}/`, {
					method: "DELETE",
					headers: { Authorization: `Bearer ${user.accessToken}` },
				})
				if (!res.ok && res.status !== 404) {
					throw new Error(`Delete project failed: ${res.status}`)
				}
			},

			async getProjects() {
				const res = await fetch(`${E2E_API_URL}/api/projects/`, {
					headers: { Authorization: `Bearer ${user.accessToken}` },
				})
				if (!res.ok) {
					throw new Error(`Get projects failed: ${res.status}`)
				}
				return res.json()
			},
		}

		await use(realProjectsPage)

		// Cleanup: delete all projects created by this test user
		try {
			const projects = await realProjectsPage.getProjects()
			for (const project of projects) {
				await realProjectsPage.deleteProject(project.id)
			}
		} catch {
			// Best-effort cleanup
		}
	},
})

export { expect } from "@playwright/test"
