import { SaveConsentPayload, SaveConsentResponse } from "@/types/cookie-consent";

const API_URL = process.env.NEXT_PUBLIC_API_BASE_URL;

/**
 * Client-side function to post cookie consent choices (accepted / rejected) to WordPress API backend.
 * Endpoint: save-consent
 */
export async function saveCookieConsent(
  payload: SaveConsentPayload
): Promise<SaveConsentResponse | null> {
  if (!API_URL) {
    console.error("NEXT_PUBLIC_API_BASE_URL is not defined");
    return null;
  }

  // Resolve language from cookies if not provided
  let lang = payload.lang;
  if (!lang && typeof document !== "undefined") {
    const matches = document.cookie.match(/(?:^|; )lang=([^;]*)/);
    lang = (matches ? matches[1] : "fr").toLowerCase();
  }

  const cleanUrl = API_URL.trim().replace(/^['"]|['"]$/g, "");
  const baseEndpoint = cleanUrl.endsWith("/")
    ? `${cleanUrl}save-consent`
    : `${cleanUrl}/save-consent`;
  const endpoint = lang ? `${baseEndpoint}?lang=${lang}` : baseEndpoint;

  try {
    const response = await fetch(endpoint, {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify({
        timestamp: new Date().toISOString(),
        lang,
        ...payload,
      }),
    });

    if (!response.ok) {
      console.error(`Failed to save cookie consent (HTTP ${response.status})`);
      return null;
    }

    const data: SaveConsentResponse = await response.json();
    return data;
  } catch (error) {
    console.error("Error saving cookie consent:", error);
    return null;
  }
}
