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 ProcessingPage {
	page: Page
	projectId: string
	processingStep: Locator
	jobId: string
}

export const test = base.extend<{ processingPage: ProcessingPage }>({
	processingPage: 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,
			`processing-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 })

		// Intercept task status polling to keep returning RUNNING (prevent auto-advance)
		await page.route("**/api/tasks/status/**", async (route) => {
			await route.fulfill({
				status: 200,
				contentType: "application/json",
				body: JSON.stringify({
					status: "RUNNING",
					progress_pct: 0,
					output_data: null,
				}),
			})
		})

		// Capture job_id from the silence-detect submission
		let capturedJobId = ""
		page.on("request", (req) => {
			if (
				req.url().includes("/api/tasks/silence-detect/") &&
				req.method() === "POST"
			) {
				// We'll get the job_id from the response
			}
		})
		page.on("response", async (res) => {
			if (
				res.url().includes("/api/tasks/silence-detect/") &&
				res.request().method() === "POST" &&
				res.status() === 200
			) {
				try {
					const body = await res.json()
					if (body?.job_id) capturedJobId = body.job_id
				} catch {
					// ignore parse errors
				}
			}
		})

		// Click "Далее" to submit silence detection
		await silenceStep.getByRole("button", { name: "Далее" }).click()

		// Wait for ProcessingStep to appear
		const processingStep = page.locator("[data-testid='ProcessingStep']")
		await processingStep.waitFor({ timeout: 10_000 })

		const processingPage: ProcessingPage = {
			page,
			projectId,
			processingStep,
			jobId: capturedJobId,
		}

		await use(processingPage)

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

export { expect } from "@playwright/test"
