import cluster from 'node:cluster';
import { pino } from 'pino';

export const log = pino({
    level: Bun.env.LOG_LEVEL ?? "info",
    transport: Bun.env.NODE_ENV != "production"
        ? { target: "pino-pretty" }
        : undefined,
});

export const env = {
    PRINTFUL_AUTH: requireEnv("PRINTFUL_AUTH"),
    PRINTFUL_STORE_ID: requireEnv("PRINTFUL_STORE_ID"),
    WEBFLOW_SITE_ID: requireEnv("WEBFLOW_SITE_ID"),
    WEBFLOW_COLLECTION_ID: requireEnv("WEBFLOW_COLLECTION_ID"),
    WEBFLOW_AUTH: requireEnv("WEBFLOW_AUTH"),
    WEBFLOW_WEBHOOK_SECRET: requireEnv("WEBFLOW_WEBHOOK_SECRET"),
    AUTH_SECRET: requireEnv("AUTH_SECRET"),
    ADMIN_PASSWORD: requireEnv("ADMIN_PASSWORD"),
    DATABASE_URL: requireEnv("DATABASE_URL"),
    NODE_ENV: optionEnv("NODE_ENV", "development"),
    LOG_LEVEL: optionEnv("LOG_LEVEL", "info"),
};

export const DEFAULT_NAME = "Default";

function requireEnv(key: string): string {
    const val = Bun.env[key];
    if (!val) {
        if (cluster.worker?.id === 1)
            log.error({ name: key }, "Missing required environment variable");
        throw new Error(`Missing required environment variable: ${key}`)
    };
    return val;
}

function optionEnv(key: string, fallback: string = ""): string {
    const val = Bun.env[key];
    if (!val) {
        if (cluster.worker?.id === 1)
            log.warn({ name: key }, `Missing optional environmental variable, falling back to "${fallback}"`)
        return fallback
    };
    return val;
}
