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 UploadPage {
	page: Page
	projectId: string
	dropZone: Locator
	fileInput: Locator
	/** Path to the minimal test MP4 file on disk */
	testVideoPath: string
	/** Upload a file by setting the hidden input (bypasses accept filter) */
	uploadFile(filePath: string): Promise<void>
	/** Upload with a synthetic buffer (name + MIME type + content) */
	uploadBuffer(name: string, mimeType: string, content: Buffer): Promise<void>
}

export const test = base.extend<{ uploadPage: UploadPage }>({
	uploadPage: 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,
			`upload-test-${suffix}`,
		)

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

		const testVideoPath = path.resolve(
			__dirname,
			"../assets/test-video.mp4",
		)

		const dropZone = page.locator("[data-testid='UploadStep']")
		const fileInput = dropZone.locator("input[type='file']")

		const uploadPage: UploadPage = {
			page,
			projectId,
			dropZone,
			fileInput,
			testVideoPath,

			async uploadFile(filePath: string) {
				await fileInput.setInputFiles(filePath)
			},

			async uploadBuffer(name: string, mimeType: string, content: Buffer) {
				await fileInput.setInputFiles({
					name,
					mimeType,
					buffer: content,
				})
			},
		}

		await use(uploadPage)

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

export { expect } from "@playwright/test"
