/**
 * Resolve DATABASE_URL from discrete DB_* vars (provider-portable).
 * Pure JS — safe in Docker entrypoints without TypeScript.
 */
function resolveDatabaseUrl(env = process.env) {
  if (env.DATABASE_URL?.trim()) {
    return env.DATABASE_URL.trim();
  }

  const host = env.DB_HOST?.trim();
  const user = env.DB_USER?.trim();
  const password = env.DB_PASSWORD ?? "";
  const name = env.DB_NAME?.trim();
  const port = (env.DB_PORT ?? "5432").trim();
  if (!host || !user || !name) return undefined;

  const sslRaw = (env.DB_SSL ?? env.SSL ?? "false").toString().toLowerCase();
  const useSsl = sslRaw === "true" || sslRaw === "1" || sslRaw === "require";
  const auth = `${encodeURIComponent(user)}:${encodeURIComponent(password)}`;
  const base = `postgresql://${auth}@${host}:${port}/${name}`;
  return useSsl ? `${base}?sslmode=require` : base;
}

const composed = resolveDatabaseUrl();
if (!composed) {
  console.error(
    "[env] DATABASE_URL is missing. Set DATABASE_URL or DB_HOST/DB_USER/DB_NAME/DB_PASSWORD.",
  );
  process.exit(1);
}

process.env.DATABASE_URL = composed;
console.info("[env] DATABASE_URL resolved");
