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

import {
	createProjectViaApi,
	deleteProjectViaApi,
	loginAsAdmin,
} from "#tests/e2e/support/auth-api"

interface SilencePage {
	page: Page
	projectId: string
	silenceStep: Locator
}

export const test = base.extend<{ silencePage: SilencePage }>({
	silencePage: async ({ page }, use) => {
		const tokens = await loginAsAdmin()

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

		const suffix = Date.now().toString(36)
		const projectId = await createProjectViaApi(
			tokens.accessToken,
			`silence-test-${suffix}`,
		)

		// Navigate to project wizard
		await page.goto(`/projects/${projectId}`)
		await page.locator("[data-testid='ProjectWizard']").waitFor()

		// Upload test video file
		const testVideoPath = path.resolve(
			__dirname,
			"../assets/test-video.mp4",
		)
		const fileInput = page
			.locator("[data-testid='UploadStep']")
			.locator("input[type='file']")
		await fileInput.setInputFiles(testVideoPath)

		// Wait for wizard to advance to Verify step
		await page
			.locator("[data-testid='VerifyStep']")
			.waitFor({ timeout: 30_000 })

		// Wait for file processing to complete
		await page
			.locator("[data-testid='VerifyStep']")
			.getByText("Готово к обработке")
			.waitFor({ timeout: 10_000 })

		// Advance to Silence Settings step
		await page
			.getByRole("button", { name: "Далее: Настройки тишины" })
			.click()

		const silenceStep = page.locator("[data-testid='SilenceSettingsStep']")
		await silenceStep.waitFor({ timeout: 10_000 })

		const silencePage: SilencePage = {
			page,
			projectId,
			silenceStep,
		}

		await use(silencePage)

		// Cleanup: delete project
		try {
			await deleteProjectViaApi(tokens.accessToken, projectId)
		} catch {
			// Best-effort cleanup
		}
	},
})

export { expect } from "@playwright/test"
