"use server";

import { headers } from "next/headers";
import { apiClient } from "@/src/app/api/client";
import { extractDomain } from "../utils/domain";
import type { CookieConsentDecision } from "../utils/cookieConsent";

/**
 * Record a visitor's response to the cookie banner in the backend.
 *
 * This runs on the website's server, so the backend sees *this server* as the
 * caller - not the visitor. The visitor's own address and browser are read
 * from the incoming request and relayed explicitly; otherwise every consent
 * row would carry the website server's IP, which is exactly what has happened
 * to policy_consents.
 *
 * The Cookie Notice version is not sent: the backend resolves it from the hub.
 */
export async function recordCookieConsentAction(input: {
  visitorId: string;
  decision: CookieConsentDecision;
}) {
  try {
    const [domain, incoming] = await Promise.all([extractDomain(), headers()]);

    // The first address in X-Forwarded-For is the client the proxy received.
    const visitorIp =
      incoming.get("x-forwarded-for")?.split(",")[0]?.trim() ||
      incoming.get("x-real-ip")?.trim() ||
      "";

    const response = await apiClient.post(
      "cookie-consents",
      {
        visitor_id: input.visitorId,
        decision: input.decision,
      },
      {
        headers: {
          "X-Domain": domain,
          ...(visitorIp ? { "X-Visitor-Ip": visitorIp } : {}),
          "X-Visitor-User-Agent": incoming.get("user-agent") || "",
        },
      },
    );

    return {
      success: Boolean(response.data?.status),
      data: response.data?.data ?? null,
    };
  } catch (error: any) {
    // Never surfaced to the visitor: their choice is already saved in their
    // browser, and the banner has closed. A failed record is logged, not shown.
    console.error(
      "[recordCookieConsentAction] Failed:",
      error?.response?.data?.message || error?.message,
    );
    return { success: false, data: null };
  }
}
