import path from "path";
import dotenv from "dotenv";

dotenv.config({ path: path.resolve(__dirname, "../../.env") });

function requireEnv(name: string): string {
  const value = process.env[name];
  if (!value) {
    throw new Error(`Missing required environment variable: ${name}`);
  }
  return value;
}

const useMockDb =
  process.env.CALENDAR_RUN_MOCK_DB === "1" ||
  process.env.CALENDAR_RUN_MOCK_DB?.toLowerCase() === "true";

export const config = {
  useMockDb,
  db: useMockDb
    ? {
        host: "mock",
        port: 5432,
        database: "mock",
        user: "mock",
        password: "mock",
      }
    : {
        host: requireEnv("DB_HOST"),
        port: parseInt(requireEnv("DB_PORT"), 10),
        database: requireEnv("DB_NAME"),
        user: requireEnv("DB_USER"),
        password: requireEnv("DB_PASSWORD"),
      },
  apiPort: parseInt(process.env.PORT || process.env.API_PORT || "3001", 10),
  /** Одно значение или несколько через запятую (прод: https://домен) */
  corsOrigin: parseCorsOrigins(),
};

function parseCorsOrigins(): string | string[] {
  const raw = process.env.CORS_ORIGIN?.trim();
  if (!raw) {
    return "http://localhost:5173";
  }
  const parts = raw.split(",").map((s) => s.trim()).filter(Boolean);
  if (parts.length === 0) {
    return "http://localhost:5173";
  }
  if (parts.length === 1) {
    return parts[0]!;
  }
  return parts;
}
