import type { SearchParams } from "@/types/data";

/**
 * Utility functions for common operations
 */

/**
 * Safely extracts string value from Next.js searchParams
 * Handles both string and array values
 */
export function getSearchParamValue(
  value: string | string[] | undefined
): string {
  if (!value) return "";
  if (Array.isArray(value)) return value[0] || "";
  return String(value);
}

/**
 * Extracts Google Ads tracking parameter from searchParams
 * Returns the first available parameter: gclid, gad_source, gad_campaignid, or gbraid
 */
export function extractGclid(searchParams: SearchParams): string | null {
  const gclidValueRaw =
    searchParams.gclid ||
    searchParams.gad_source ||
    searchParams.gad_campaignid ||
    searchParams.gbraid;

  const value = getSearchParamValue(gclidValueRaw);
  return value || null;
}

/**
 * Gets client IP address from request headers
 * Checks common proxy headers: x-forwarded-for, x-real-ip
 */
export function getClientIp(headers: Headers): string | null {
  const forwardedFor = headers.get("x-forwarded-for");
  const realIp = headers.get("x-real-ip");
  return forwardedFor?.split(",")[0]?.trim() || realIp || null;
}

/**
 * Creates a slug from a string
 */
export function createSlug(text: string): string {
  return text.toLowerCase().replace(/[^a-z0-9]+/g, "-");
}

