export type AttributionPayload = {
  src?: string;
  campaign?: string;
  creative?: string;
  variant?: string;
  click_id?: string;
  slug?: string;
  exp?: string;
  ad_type?: string;
  utm_source?: string;
  utm_medium?: string;
  utm_campaign?: string;
  utm_content?: string;
  utm_term?: string;
  landing_path?: string;
  full_path?: string;
  referrer?: string;
  session_id?: string;
  [key: string]: unknown;
};

export function getClientIpFromHeaders(headers: Headers): string | null {
  const forwarded = headers.get("x-forwarded-for")
    || headers.get("cf-connecting-ip")
    || headers.get("x-real-ip");

  if (!forwarded) {
    return null;
  }

  return forwarded.split(",")[0]?.trim() || null;
}

export function compactAttribution(payload: AttributionPayload | undefined | null): AttributionPayload | null {
  if (!payload) {
    return null;
  }

  const filtered = Object.fromEntries(
    Object.entries(payload).filter(([, value]) => value !== undefined && value !== null && value !== "")
  );

  return Object.keys(filtered).length > 0 ? filtered : null;
}
