const DISALLOWED_PRODUCTION_SECRETS = new Set([
  "dev-secret-change-in-production",
  "changeme",
  "change-me",
  "default",
  "secret",
]);

type RuntimeEnv = Partial<Record<string, string | undefined>>;

function readEnvValue(env: RuntimeEnv, ...names: string[]): string | null {
  for (const name of names) {
    const value = env[name]?.trim();
    if (value) {
      return value;
    }
  }

  return null;
}

function isProductionLike(env: RuntimeEnv): boolean {
  return (env.NODE_ENV ?? "").trim() === "production";
}

function isLocalhost(hostname: string): boolean {
  return hostname === "localhost" || hostname === "127.0.0.1" || hostname === "::1";
}

export function getRuntimeEnvViolations(env: RuntimeEnv = process.env): string[] {
  if (!isProductionLike(env)) {
    return [];
  }

  const violations: string[] = [];
  const authSecret = readEnvValue(env, "AUTH_SECRET", "NEXTAUTH_SECRET");
  const authUrl = readEnvValue(env, "AUTH_URL", "NEXTAUTH_URL");

  if (!authSecret) {
    violations.push("AUTH_SECRET or NEXTAUTH_SECRET must be set in production.");
  } else if (DISALLOWED_PRODUCTION_SECRETS.has(authSecret)) {
    violations.push("AUTH_SECRET or NEXTAUTH_SECRET must not use a known development placeholder in production.");
  }

  if ((env.E2E_TEST_MODE ?? "").trim() === "true") {
    violations.push("E2E_TEST_MODE must not be 'true' in production — it disables all rate limiting and session controls.");
  }

  if (!authUrl) {
    violations.push("AUTH_URL or NEXTAUTH_URL must be set in production.");
  } else {
    try {
      const parsed = new URL(authUrl);
      if (parsed.protocol !== "https:" && !isLocalhost(parsed.hostname)) {
        violations.push("AUTH_URL or NEXTAUTH_URL must use https in production.");
      }
    } catch {
      violations.push("AUTH_URL or NEXTAUTH_URL must be a valid URL in production.");
    }
  }

  return violations;
}

export function assertSecureRuntimeEnv(env: RuntimeEnv = process.env): void {
  const violations = getRuntimeEnvViolations(env);
  if (violations.length === 0) {
    return;
  }

  throw new Error(`Invalid production runtime configuration: ${violations.join(" ")}`);
}
