export type RuntimeEnv = {
  DATABASE_URL?: string;
  MYSQL_HOST?: string;
  MYSQL_PORT?: string;
  MYSQL_USER?: string;
  MYSQL_PASSWORD?: string;
  MYSQL_DATABASE?: string;
  UPLOAD_DIR?: string;
  APP_ORIGIN?: string;
  KOC_PORTAL_URL?: string;
  SUPER_ADMIN_USERNAME?: string;
  SUPER_ADMIN_PASSWORD?: string;
  ADMIN_INTERNAL_TOKEN?: string;
  KOC_MCP_API_KEY?: string;
  KOC_LOOP_MCP_API_KEY?: string;
  MCP_API_KEY?: string;
  FEISHU_APP_ID?: string;
  FEISHU_APP_SECRET?: string;
  AI_TOOL_CENTER_MCP_URL?: string;
  AI_TOOL_CENTER_MCP_KEY?: string;
  COLLECTION_MCP_URL?: string;
  COLLECTION_MCP_KEY?: string;
  WECOM_CORP_ID?: string;
  WECOM_AGENT_ID?: string;
  WECOM_SECRET?: string;
  WECOM_ROBOT_WEBHOOK?: string;
  WECOM_NOTIFY_DUE_DAYS?: string;
  WECOM_NOTIFY_ENABLED?: string;
  SEED_DEMO_DATA?: string;
  ENABLE_SCHEDULER?: string;
};

export function getRuntimeEnv(): RuntimeEnv {
  return process.env as RuntimeEnv;
}

export function getDatabaseUrl() {
  const env = getRuntimeEnv();
  if (env.DATABASE_URL) return env.DATABASE_URL;
  const host = env.MYSQL_HOST ?? "127.0.0.1";
  const port = env.MYSQL_PORT ?? "3306";
  const user = encodeURIComponent(env.MYSQL_USER ?? "koc");
  const password = encodeURIComponent(env.MYSQL_PASSWORD ?? "");
  const database = env.MYSQL_DATABASE ?? "koc_loop";
  return `mysql://${user}:${password}@${host}:${port}/${database}`;
}

export function isEnabled(value: string | undefined, defaultValue = false) {
  if (value === undefined || value === "") return defaultValue;
  return !["0", "false", "no", "off"].includes(value.toLowerCase());
}
