const DEV_LIKE_ENVIRONMENTS = ["development", "staging", "qa"];
function isDebugEnabled() {
  return process.env.NEXTSPARK_DEBUG_CORS === "true";
}
function normalizeOrigin(origin) {
  if (!origin || typeof origin !== "string") {
    return "";
  }
  try {
    const url = new URL(origin);
    return url.origin;
  } catch {
    return origin.toLowerCase().replace(/\/+$/, "");
  }
}
function normalizeCorsEnvironment(env) {
  const normalized = env.toLowerCase();
  if (DEV_LIKE_ENVIRONMENTS.includes(normalized)) {
    return "development";
  }
  if (normalized === "production") {
    return "production";
  }
  if (isDebugEnabled()) {
    console.log(`[cors] Unknown environment "${env}", defaulting to development`);
  }
  return "development";
}
function getCorsOrigins(config, env = process.env.NODE_ENV || "development") {
  var _a;
  const key = normalizeCorsEnvironment(env);
  if (isDebugEnabled()) {
    console.log(`[cors] Environment: ${env} -> normalized: ${key}`);
  }
  const coreOrigins = [...config.api.cors.allowedOrigins[key] || []];
  const themeOrigins = [...((_a = config.api.cors.additionalOrigins) == null ? void 0 : _a[key]) || []];
  const envVar = process.env.CORS_ADDITIONAL_ORIGINS || "";
  const envOrigins = envVar.split(",").map((o) => o.trim()).filter(Boolean);
  const appUrl = process.env.NEXT_PUBLIC_APP_URL;
  const authUrl = process.env.BETTER_AUTH_URL;
  const baseOrigins = [];
  if (appUrl) baseOrigins.push(appUrl);
  if (authUrl && authUrl !== appUrl) baseOrigins.push(authUrl);
  const allOrigins = [...baseOrigins, ...coreOrigins, ...themeOrigins, ...envOrigins];
  const origins = [...new Set(allOrigins.map(normalizeOrigin))];
  if (isDebugEnabled()) {
    console.log(`[cors] Merged origins (${origins.length}):`, origins);
    console.log(`[cors]   - Base origins: ${baseOrigins.length}`);
    console.log(`[cors]   - Core origins: ${coreOrigins.length}`);
    console.log(`[cors]   - Theme origins: ${themeOrigins.length}`);
    console.log(`[cors]   - Env origins: ${envOrigins.length}`);
    for (const origin of origins) {
      if (!origin.startsWith("http://") && !origin.startsWith("https://")) {
        console.warn(`[cors] Invalid origin format: "${origin}" (must start with http:// or https://)`);
      }
    }
  }
  return origins;
}
export {
  getCorsOrigins,
  normalizeCorsEnvironment,
  normalizeOrigin
};
