import dotenv from "dotenv";
dotenv.config();

// Set timezone for Date operations — all attendance/time records are in Czech local time
process.env.TZ = process.env.TZ || "Europe/Prague";

// Override Date.toJSON so JSON.stringify outputs local time (Europe/Prague).
// This is intentional and required for PHP migration compatibility: the legacy
// PHP API returned local Czech times, and the frontend relies on this format.
// Prisma stores UTC in MySQL DATETIME columns. When reading, it creates
// JS Date objects with correct UTC internals. The default toJSON() calls
// toISOString() which returns UTC — this override uses local getters instead,
// so the frontend always receives times in the user's timezone.
Date.prototype.toJSON = function () {
  const y = this.getFullYear();
  const m = String(this.getMonth() + 1).padStart(2, "0");
  const d = String(this.getDate()).padStart(2, "0");
  const h = String(this.getHours()).padStart(2, "0");
  const min = String(this.getMinutes()).padStart(2, "0");
  const s = String(this.getSeconds()).padStart(2, "0");
  return `${y}-${m}-${d}T${h}:${min}:${s}`;
};

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

export const config = {
  port: parseInt(process.env.PORT || "3001", 10),
  host: process.env.HOST || "127.0.0.1",
  appEnv: process.env.APP_ENV || "local",
  isProduction: process.env.APP_ENV === "production",

  db: {
    url: required("DATABASE_URL"),
  },

  jwt: {
    secret: required("JWT_SECRET"),
    accessTokenExpiry: parseInt(process.env.ACCESS_TOKEN_EXPIRY || "900", 10),
    refreshTokenSessionExpiry: parseInt(
      process.env.REFRESH_TOKEN_SESSION_EXPIRY || "3600",
      10,
    ),
    refreshTokenRememberExpiry: parseInt(
      process.env.REFRESH_TOKEN_REMEMBER_EXPIRY || "2592000",
      10,
    ),
  },

  totp: {
    encryptionKey: required("TOTP_ENCRYPTION_KEY"),
    algorithm: (process.env.TOTP_ALGORITHM || "SHA1") as "SHA1",
    digits: Math.max(6, parseInt(process.env.TOTP_DIGITS || "6", 10) || 6),
    period: Math.max(15, parseInt(process.env.TOTP_PERIOD || "30", 10) || 30),
    loginTokenExpiryMinutes: Math.max(
      1,
      parseInt(process.env.LOGIN_TOKEN_EXPIRY_MINUTES || "5", 10) || 5,
    ),
  },

  anthropic: {
    apiKey: process.env.ANTHROPIC_API_KEY || "",
  },

  nas: {
    path: process.env.NAS_PATH || "Z:/02_PROJEKTY",
    invoicesPath:
      process.env.NAS_INVOICES || process.env.NAS_FINANCIALS_PATH || "",
    ordersPath: process.env.NAS_ORDERS || "",
    offersPath: process.env.NAS_OFFERS_PATH || "",
    maxUploadSize: (() => {
      const parsed = parseInt(process.env.MAX_UPLOAD_SIZE || "52428800", 10);
      if (Number.isNaN(parsed) || parsed <= 0) {
        console.warn("Invalid MAX_UPLOAD_SIZE, using default 52428800");
        return 52428800;
      }
      return parsed;
    })(),
  },

  email: {
    contactTo: process.env.CONTACT_EMAIL_TO || "",
    contactFrom: process.env.CONTACT_EMAIL_FROM || "",
    smtpFrom: process.env.SMTP_FROM || "",
    smtpFromName: process.env.SMTP_FROM_NAME || "",
    leaveNotify: process.env.LEAVE_NOTIFY_EMAIL || "",
    invoiceAlert: process.env.INVOICE_ALERT_EMAIL || "",
  },

  appUrl: process.env.APP_URL || "",

  cors: {
    origins: (process.env.CORS_ORIGINS || "").split(",").filter(Boolean),
  },

  rateLimit: {
    max: Math.max(1, parseInt(process.env.RATE_LIMIT_MAX || "300", 10) || 300),
    timeWindow: process.env.RATE_LIMIT_WINDOW || "1 minute",
    login: Math.max(
      1,
      parseInt(process.env.RATE_LIMIT_LOGIN || "20", 10) || 20,
    ),
    loginTotp: Math.max(
      1,
      parseInt(process.env.RATE_LIMIT_TOTP || "5", 10) || 5,
    ),
    refresh: Math.max(
      1,
      parseInt(process.env.RATE_LIMIT_REFRESH || "10", 10) || 10,
    ),
  },

  trustProxy: (process.env.TRUST_PROXY || "")
    .split(",")
    .map((s) => s.trim())
    .filter(Boolean),

  security: {
    bcryptCost: 12,
  },
} as const;

const HEX64_RE = /^[0-9a-fA-F]{64}$/;
if (!HEX64_RE.test(config.jwt.secret)) {
  throw new Error("JWT_SECRET must be a 64-character hex string");
}
if (!HEX64_RE.test(config.totp.encryptionKey)) {
  throw new Error("TOTP_ENCRYPTION_KEY must be a 64-character hex string");
}
if (Number.isNaN(config.port) || config.port < 1 || config.port > 65535) {
  throw new Error("PORT must be a valid TCP port (1-65535)");
}
if (
  Number.isNaN(config.jwt.accessTokenExpiry) ||
  config.jwt.accessTokenExpiry <= 0
) {
  throw new Error("ACCESS_TOKEN_EXPIRY must be a positive integer");
}
if (
  Number.isNaN(config.jwt.refreshTokenSessionExpiry) ||
  config.jwt.refreshTokenSessionExpiry <= 0
) {
  throw new Error("REFRESH_TOKEN_SESSION_EXPIRY must be a positive integer");
}
if (
  Number.isNaN(config.jwt.refreshTokenRememberExpiry) ||
  config.jwt.refreshTokenRememberExpiry <= 0
) {
  throw new Error("REFRESH_TOKEN_REMEMBER_EXPIRY must be a positive integer");
}
