import dotenv from "dotenv";

dotenv.config();

const parseBoolean = (value, fallback = false) => {
  if (value === undefined || value === null || value === "") {
    return fallback;
  }

  return ["1", "true", "yes", "on"].includes(String(value).toLowerCase());
};

const required = ["PORT", "DB_URL", "JWT_SECRET"];

required.forEach((key) => {
  if (!process.env[key]) {
    throw new Error(`Missing required environment variable: ${key}`);
  }
});

export const env = {
  nodeEnv: process.env.NODE_ENV || "development",
  port: Number(process.env.PORT) || 5000,
  dbUrl: process.env.DB_URL,
  dbSsl: parseBoolean(process.env.DB_SSL, process.env.NODE_ENV === "production"),
  dbSslRejectUnauthorized: parseBoolean(process.env.DB_SSL_REJECT_UNAUTHORIZED, false),
  jwtSecret: process.env.JWT_SECRET,
  clientUrl: process.env.CLIENT_URL || "http://localhost:5173",
  clientUrls: String(process.env.CLIENT_URLS || process.env.CLIENT_URL || "http://localhost:5173")
    .split(",")
    .map((item) => item.trim())
    .filter(Boolean),
  jwtCookieName: process.env.JWT_COOKIE_NAME || "scf_token",
  jwtRefreshCookieName:
    process.env.JWT_REFRESH_COOKIE_NAME || "scf_refresh_token",
  refreshTokenTtlDays: Math.max(Number(process.env.JWT_REFRESH_TTL_DAYS) || 30, 1),
  pgDumpCommand: process.env.PG_DUMP_COMMAND || "pg_dump",
  disablePdfExports: parseBoolean(process.env.DISABLE_PDF_EXPORTS, false),
  trackingDebug: String(process.env.TRACKING_DEBUG || "").toLowerCase() === "true",
  freeKioskMqttHost: process.env.FREEKIOSK_MQTT_HOST || "127.0.0.1",
  freeKioskMqttPort: Number(process.env.FREEKIOSK_MQTT_PORT) || 1883,
  freeKioskMqttUsername: process.env.FREEKIOSK_MQTT_USERNAME || "",
  freeKioskMqttPassword: process.env.FREEKIOSK_MQTT_PASSWORD || "",
  freeKioskMqttBaseTopic: process.env.FREEKIOSK_MQTT_BASE_TOPIC || "freekiosk",
};
