const path = require("path");

const root = path.resolve(__dirname, "..");

function bool(value, fallback = false) {
  if (value === undefined || value === null || value === "") return fallback;
  return ["1", "true", "yes", "on"].includes(String(value).toLowerCase());
}

function fromRoot(value, fallback) {
  const selected = value || fallback;
  return path.isAbsolute(selected) ? selected : path.join(root, selected);
}

const env = process.env.NODE_ENV || "development";
const production = env === "production";
const sessionSecret = process.env.SESSION_SECRET || "";
const setupToken = process.env.SETUP_TOKEN || "";

if (production) {
  if (!sessionSecret || sessionSecret === "development-only-change-me" || sessionSecret.length < 32) {
    throw new Error("Refusing to start in production without a strong SESSION_SECRET of at least 32 characters.");
  }
  if (!setupToken || setupToken.length < 24) {
    throw new Error("Refusing to start in production without a SETUP_TOKEN of at least 24 characters.");
  }
}

module.exports = {
  root,
  env,
  port: Number(process.env.PORT || 3000),
  baseUrl: process.env.APP_BASE_URL || "http://localhost:3000",
  primaryDomain: process.env.PRIMARY_DOMAIN || "debbiewindlerseamstress.com",
  secondaryDomain: process.env.SECONDARY_DOMAIN || "debbiewindler.com",
  sessionSecret: sessionSecret || "development-only-change-me",
  setupToken,
  trustProxy: process.env.TRUST_PROXY || "loopback",
  databasePath: fromRoot(process.env.DATABASE_PATH, "./storage/site.sqlite"),
  uploadDir: fromRoot(process.env.UPLOAD_DIR, "./public/uploads"),
  backupDir: fromRoot(process.env.BACKUP_DIR, "./storage/backups"),
  smtp: {
    host: process.env.SMTP_HOST || "",
    port: Number(process.env.SMTP_PORT || 587),
    secure: bool(process.env.SMTP_SECURE, false),
    user: process.env.SMTP_USER || "",
    pass: process.env.SMTP_PASS || "",
    from: process.env.SMTP_FROM || "Debbie Windler Seamstress <website@debbiewindlerseamstress.com>",
    ownerEmail: process.env.OWNER_EMAIL || ""
  },
  captcha: {
    enabled: bool(process.env.CAPTCHA_ENABLED, false),
    siteKey: process.env.CAPTCHA_SITE_KEY || "",
    secretKey: process.env.CAPTCHA_SECRET_KEY || ""
  },
  production
};
