import "server-only";
import { getEnv } from "@/server/env";

/**
 * Protección CSRF para Route Handlers que usan la cookie de sesión.
 * (Las Server Actions ya comparan Origin con Host de forma nativa en Next.js.)
 *
 * Exige que la petición declare un Origin igual al del sitio. Junto con SameSite=Lax
 * en la cookie, bloquea formularios y fetch desde otros dominios.
 */
export function isSameOriginRequest(request: Request): boolean {
  const origin = request.headers.get("origin");
  if (!origin) return false;

  let originUrl: URL;
  try {
    originUrl = new URL(origin);
  } catch {
    return false;
  }

  const allowed = new Set<string>([new URL(getEnv().NEXT_PUBLIC_SITE_URL).origin]);
  const host = request.headers.get("x-forwarded-host") ?? request.headers.get("host");
  if (host) {
    const proto =
      request.headers.get("x-forwarded-proto") ?? new URL(request.url).protocol.replace(":", "");
    allowed.add(`${proto}://${host}`);
  }
  return allowed.has(originUrl.origin);
}
