export type AuthConfig = {
  origin: string;
  clientId: string;
  clientSecret: string;
  cookieSecret: string;
};

export function readAuthConfig(env = process.env): AuthConfig {
  const production = env.NODE_ENV === "production";
  const configuredOrigin = env.APP_ORIGIN?.trim();
  if (production && !configuredOrigin) {
    throw new Error("Set APP_ORIGIN in .env.production or the process environment before starting in production.");
  }
  const origin = configuredOrigin || `http://127.0.0.1:${env.PORT ?? 3000}`;
  let url: URL;
  try {
    url = new URL(origin);
  } catch {
    throw new Error("APP_ORIGIN must be a valid origin.");
  }
  const local = ["localhost", "127.0.0.1", "[::1]"].includes(url.hostname);
  if (url.username || url.password || url.pathname !== "/" || url.search || url.hash ||
      (url.protocol !== "https:" && !(local && url.protocol === "http:"))) {
    throw new Error("APP_ORIGIN must be an HTTPS origin (HTTP is allowed for localhost).");
  }
  return {
    origin: url.origin,
    clientId: env.DISCORD_CLIENT_ID ?? "",
    clientSecret: env.DISCORD_CLIENT_SECRET ?? "",
    cookieSecret: env.AUTH_COOKIE_SECRET ?? "",
  };
}

export function isAuthConfigured(config: AuthConfig) {
  return Boolean(config.clientId && config.clientSecret && config.cookieSecret.length >= 32);
}
