import { test as base, expect, APIRequestContext } from "@playwright/test"
import { ensureTestUser, type TestUserCredentials } from "./helpers/test-user"

const API_BASE = "/api"

interface ActionSuccess {
    success: true
    [key: string]: unknown
}

interface ActionError {
    error: string
}

type ApiWorkerFixtures = {
    testUser: TestUserCredentials
}

type ApiFixtures = {
    api: APIRequestContext
    authedApi: APIRequestContext
    accessToken: string
}

export const test = base.extend<ApiFixtures, ApiWorkerFixtures>({
    testUser: [
        async ({ playwright }, use) => {
            const baseURL = process.env.CODING_URL || "https://localhost:3000"
            const user = await ensureTestUser(baseURL)
            await use(user)
        },
        { scope: "worker" },
    ],

    api: async ({ request }, use) => {
        await use(request)
    },

    accessToken: async ({ testUser }, use) => {
        await use(testUser.accessToken)
    },

    authedApi: async ({ playwright, baseURL, accessToken }, use) => {
        const ctx = await playwright.request.newContext({
            baseURL: baseURL!,
            ignoreHTTPSErrors: true,
            extraHTTPHeaders: {
                Authorization: `Bearer ${accessToken}`,
            },
        })
        await use(ctx)
        await ctx.dispose()
    },
})

export { expect, API_BASE }
export type { ActionSuccess, ActionError }
