import { request } from "@playwright/test"
import { ensureSeededTestContent } from "./api/helpers/seed-data"
import { TEST_BASE_URL } from "./fixtures/test-constants"

async function globalSetup() {
    const baseURL = TEST_BASE_URL

    // Seed cleanup/creation stays run-scoped here so all workers consume the
    // same deterministic dataset instead of racing on shared test records.

    const ctx = await request.newContext({
        baseURL,
        ignoreHTTPSErrors: true,
        extraHTTPHeaders: {
            "User-Agent": "Playwright",
        },
    })

    try {
        const res = await ctx.get("/")
        if (!res.ok()) {
            throw new Error(`Dev environment at ${baseURL} returned ${res.status()}`)
        } else {
            console.log(`Playwright setup: dev environment reachable at ${baseURL}`)
        }

        const apiProbe = await ctx.get("/api/content?limit=1")
        const contentType = apiProbe.headers()["content-type"] || ""
        if (!apiProbe.ok() || contentType.includes("text/html")) {
            throw new Error(
                `Playwright seed setup needs a base URL with working /api access. Current base URL ${baseURL} returned ${apiProbe.status()} ${contentType || "without content-type"} for /api/content.`
            )
        }

        const result = await ensureSeededTestContent(baseURL)
        console.log(
            `Playwright setup: seeded deterministic test data (deleted ${result.deleted}, created ${result.created})`
        )
    } finally {
        await ctx.dispose()
    }
}

export default globalSetup
