/** Request-level protections: client IP, same-origin check for cookie-authenticated writes (CSRF), IP allowlists. */

export function clientIp(h: Headers) {
  return h.get("x-forwarded-for")?.split(",")[0]?.trim() || h.get("x-real-ip") || null;
}

/**
 * Cookie sessions are SameSite=Lax; on top of that, state-changing browser requests must come from our own origin.
 * Requests without an Origin header (server-to-server, curl, API keys) are not browser CSRF and pass.
 */
export function sameOrigin(h: Headers) {
  const origin = h.get("origin");
  if (!origin || origin === "null") return origin !== "null";
  let o: URL;
  try { o = new URL(origin); } catch { return false; }
  const host = (h.get("x-forwarded-host") ?? h.get("host") ?? "").split(",")[0]!.trim().toLowerCase();
  if (o.host.toLowerCase() === host) return true;
  const allowed = [process.env.APP_URL, process.env.NEXT_PUBLIC_APP_URL, ...(process.env.EXTRA_APP_HOSTS ?? "").split(",").map((x) => x.trim() && `https://${x.trim()}`)]
    .filter(Boolean).map((u) => { try { return new URL(String(u)).host.toLowerCase(); } catch { return ""; } });
  return allowed.includes(o.host.toLowerCase());
}

const v4 = (ip: string) => {
  const p = ip.split(".").map(Number);
  return p.length === 4 && p.every((n) => Number.isInteger(n) && n >= 0 && n <= 255) ? ((p[0]! << 24) >>> 0) + (p[1]! << 16) + (p[2]! << 8) + p[3]! : null;
};

/** Entries: exact IPv4/IPv6 addresses or IPv4 CIDR ranges (e.g. 103.4.145.0/24). Empty list = allow all. */
export function ipAllowed(ip: string | null | undefined, list?: string[] | null) {
  const entries = (list ?? []).map((x) => x.trim()).filter(Boolean);
  if (!entries.length) return true;
  if (!ip) return false;
  const clean = ip.replace(/^::ffff:/, "");
  for (const e of entries) {
    if (!e.includes("/")) { if (e.toLowerCase() === clean.toLowerCase()) return true; continue; }
    const [base, bitsRaw] = e.split("/");
    const bits = Number(bitsRaw);
    const a = v4(clean), b = v4(base!);
    if (a === null || b === null || !(bits >= 0 && bits <= 32)) continue;
    const mask = bits === 0 ? 0 : (~0 << (32 - bits)) >>> 0;
    if (((a & mask) >>> 0) === ((b & mask) >>> 0)) return true;
  }
  return false;
}

export function validIpEntry(e: string) {
  const t = e.trim();
  if (t.includes("/")) { const [b, bits] = t.split("/"); return v4(b!) !== null && Number(bits) >= 0 && Number(bits) <= 32; }
  return v4(t) !== null || /^[0-9a-f:]+$/i.test(t);
}

/** Optional breached-password check (Have I Been Pwned range API — only the first 5 hex chars of the SHA-1 leave the server). */
export async function passwordBreached(password: string) {
  if (process.env.PASSWORD_BREACH_CHECK === "false") return false;
  try {
    const { createHash } = await import("node:crypto");
    const h = createHash("sha1").update(password).digest("hex").toUpperCase();
    const r = await fetch(`https://api.pwnedpasswords.com/range/${h.slice(0, 5)}`, { headers: { "Add-Padding": "true" }, signal: AbortSignal.timeout(2500) });
    if (!r.ok) return false;
    const suffix = h.slice(5);
    return (await r.text()).split("\n").some((line) => line.split(":")[0]?.trim() === suffix && Number(line.split(":")[1]) > 0);
  } catch {
    return false; // fail open: availability of a third-party service must not block sign-up
  }
}
