import { cookies } from "next/headers";
import type { SearchParams } from "@/types/data";
import { getSearchParamValue } from "./utils";

const GOOGLE_ADS_PARAMS_COOKIE = "google-ads-params";
const COOKIE_MAX_AGE = 60 * 60 * 24; // 24 hours

/**
 * Google Ads parameters that need to be persisted
 */
const PERSISTENT_PARAMS = [
  "gad_campaignid",
  "gad_source",
  "gclid",
  "gbraid",
  "wbraid",
] as const;

/**
 * Stores Google Ads parameters in a cookie for persistence across page navigations
 */
export async function persistGoogleAdsParams(searchParams: SearchParams): Promise<void> {
  const params: Record<string, string> = {};
  let hasAnyParam = false;

  // Extract all Google Ads parameters from the current URL
  for (const param of PERSISTENT_PARAMS) {
    const value = getSearchParamValue(searchParams[param]);
    if (value) {
      params[param] = value;
      hasAnyParam = true;
    }
  }

  const cookieStore = await cookies();

  if (hasAnyParam) {
    // Store parameters in cookie as JSON
    cookieStore.set(GOOGLE_ADS_PARAMS_COOKIE, JSON.stringify(params), {
      path: "/",
      maxAge: COOKIE_MAX_AGE,
      sameSite: "lax",
      httpOnly: false, // Allow client-side access if needed
    });
  }
}

/**
 * Retrieves persisted Google Ads parameters from cookie
 * Returns null if no parameters are stored
 */
export async function getPersistedGoogleAdsParams(): Promise<SearchParams | null> {
  const cookieStore = await cookies();
  const cookie = cookieStore.get(GOOGLE_ADS_PARAMS_COOKIE);

  if (!cookie?.value) {
    return null;
  }

  try {
    const params = JSON.parse(cookie.value) as Record<string, string>;
    return params as SearchParams;
  } catch {
    return null;
  }
}

/**
 * Merges current URL searchParams with persisted cookie params
 * Current URL params take precedence if they exist
 */
export async function mergeGoogleAdsParams(
  currentSearchParams: SearchParams
): Promise<SearchParams> {
  const persisted = await getPersistedGoogleAdsParams();
  const merged: SearchParams = { ...persisted };

  // Current URL params override persisted params
  for (const param of PERSISTENT_PARAMS) {
    const currentValue = getSearchParamValue(currentSearchParams[param]);
    if (currentValue) {
      merged[param] = currentValue;
    }
  }

  return merged;
}

