import { APIRequestContext, request } from "@playwright/test"
import { TEST_USER } from "../../fixtures/test-constants"

const API_BASE = "/api"

export interface TestUserCredentials {
    email: string
    password: string
    accessToken: string
    firstName: string
    lastName: string
}

/**
 * Login a user via the tibi action endpoint.
 * Returns the access token or null on failure.
 */
export async function loginUser(baseURL: string, email: string, password: string): Promise<string | null> {
    const ctx = await request.newContext({
        baseURL,
        ignoreHTTPSErrors: true,
    })

    try {
        const res = await ctx.post(`${API_BASE}/action`, {
            params: { cmd: "login" },
            data: { email, password },
        })
        if (!res.ok()) return null
        const body = await res.json()
        return body.accessToken || null
    } finally {
        await ctx.dispose()
    }
}

/**
 * Ensure the test user exists and is logged in.
 * Tries login first; if that fails, logs a warning (registration must be
 * implemented per project or the user must be seeded via globalSetup).
 */
export async function ensureTestUser(baseURL: string): Promise<TestUserCredentials> {
    const email = TEST_USER.email
    const password = TEST_USER.password

    const token = await loginUser(baseURL, email, password)
    if (token) {
        return {
            email,
            password,
            accessToken: token,
            firstName: TEST_USER.firstName,
            lastName: TEST_USER.lastName,
        }
    }

    // If login fails, the test user doesn't exist yet.
    // Implement project-specific registration here, or seed via globalSetup.
    console.warn(
        `⚠️ Test user ${email} could not be logged in. ` +
            `Either implement registration in test-user.ts or seed the user via globalSetup.`
    )

    // Return a placeholder – tests requiring auth will fail gracefully
    return {
        email,
        password,
        accessToken: "",
        firstName: TEST_USER.firstName,
        lastName: TEST_USER.lastName,
    }
}
