import fs from "node:fs"
import path from "node:path"

/**
 * Zentrale Test-Konstanten für alle Tests.
 *
 * Aktuell relevant fuer das deterministische Playwright-Setup:
 * - ADMIN_TOKEN: statischer Token aus api/config.yml.env fuer Seed/Cleanup
 * - TEST_BASE_URL: bevorzugt CODING_URL aus env/.env
 * - SEEDED_TEST_CONTENT: feste Routen fuer API- und E2E-Tests
 */

export const TEST_USER = {
    email: "playwright-e2e@test.example.com",
    password: "PlaywrightTest1",
    firstName: "Playwright",
    lastName: "E2E",
} as const

function loadAdminTokenFromEnvFile(): string | undefined {
    const envFilePath = path.resolve(process.cwd(), "api/config.yml.env")
    if (!fs.existsSync(envFilePath)) return undefined

    const raw = fs.readFileSync(envFilePath, "utf8")
    const line = raw
        .split(/\r?\n/)
        .find((entry) => entry.startsWith("ADMIN_TOKEN=") && entry.trim().length > "ADMIN_TOKEN=".length)

    return line ? line.slice("ADMIN_TOKEN=".length).trim() : undefined
}

function loadProjectEnvValue(key: string): string | undefined {
    const envFilePath = path.resolve(process.cwd(), ".env")
    if (!fs.existsSync(envFilePath)) return undefined

    const raw = fs.readFileSync(envFilePath, "utf8")
    const prefix = `${key}=`
    const line = raw.split(/\r?\n/).find((entry) => entry.startsWith(prefix) && entry.trim().length > prefix.length)
    if (!line) return undefined

    return line.slice(prefix.length).trim()
}

export const ADMIN_TOKEN = process.env.ADMIN_TOKEN || loadAdminTokenFromEnvFile() || "CHANGE_ME"
export const API_BASE = "/api"
export const TEST_BASE_URL = process.env.CODING_URL || loadProjectEnvValue("CODING_URL") || "http://localhost:3000"
export const TEST_ADMIN_BASE_URL =
    process.env.CODING_TIBIADMIN_URL || loadProjectEnvValue("CODING_TIBIADMIN_URL") || "http://localhost:3000"

export const ADMIN_UI_CREDENTIALS = {
    username: process.env.ADMIN_UI_USERNAME || "admin",
    password: process.env.ADMIN_UI_PASSWORD || "admin",
} as const

export const SEEDED_TEST_CONTENT = {
    home: {
        translationKey: "pw-e2e-home",
        path: "/playwright-e2e-home",
    },
    pagebuilderPreview: {
        translationKey: "pw-e2e-pagebuilder-preview",
        path: "/playwright-e2e-pagebuilder-preview",
    },
    contact: {
        translationKey: "pw-e2e-contact",
        path: "/playwright-e2e-contact",
    },
    inactive: {
        translationKey: "pw-e2e-inactive",
        path: "/playwright-e2e-inactive",
    },
} as const

export const BASIC_AUTH = {
    username: process.env.BASIC_AUTH_USER || "web",
    password: process.env.BASIC_AUTH_PASS || "web",
} as const
