import { cleanupAllTestData, disposeAdminApi } from "./api/helpers/admin-api"
import { deleteAllEmails, disposeMailDev } from "./api/helpers/maildev"
import { cleanupSeededTestContent } from "./api/helpers/seed-data"
import { TEST_BASE_URL } from "./fixtures/test-constants"

async function globalTeardown() {
    const baseURL = TEST_BASE_URL

    // Final seed cleanup also stays run-scoped here. Per-test or per-worker
    // cleanup would race with parallel workers against the shared seeded data.

    try {
        const probeContext = await import("@playwright/test").then(({ request }) =>
            request.newContext({ baseURL, ignoreHTTPSErrors: true })
        )
        const apiProbe = await probeContext.get("/api/content?limit=1")
        const contentType = apiProbe.headers()["content-type"] || ""
        await probeContext.dispose()

        if (!apiProbe.ok() || contentType.includes("text/html")) {
            console.warn(
                `Playwright teardown: skipped seeded cleanup because ${baseURL} has no usable /api endpoint (${apiProbe.status()} ${contentType || "without content-type"})`
            )
            return
        }

        const deletedSeedEntries = await cleanupSeededTestContent(baseURL)
        const result = await cleanupAllTestData(baseURL)
        if (deletedSeedEntries > 0 || result.users > 0) {
            console.log(
                `Playwright teardown: deleted ${deletedSeedEntries} seeded content/media entries and ${result.users} test users`
            )
        }
    } catch (err) {
        console.warn("Playwright teardown: test data cleanup failed:", err)
    }

    try {
        await deleteAllEmails()
    } catch {
        // MailDev cleanup is optional.
    }

    await Promise.all([disposeAdminApi(), disposeMailDev()])
}

export default globalTeardown
