import type { ConsentCookieState } from "./types";

export const CONSENT_COOKIE_NAME = "__consent_state";
const COOKIE_VERSION = 1 as const;
const ONE_YEAR_SECONDS = 365 * 24 * 60 * 60;

export function readConsentCookie(): ConsentCookieState | null {
  if (typeof document === "undefined") return null;

  const cookies = document.cookie.split(";");
  for (const raw of cookies) {
    const eqIdx = raw.indexOf("=");
    if (eqIdx === -1) continue;
    const name = raw.slice(0, eqIdx).trim();
    if (name !== CONSENT_COOKIE_NAME) continue;

    try {
      const decoded = decodeURIComponent(raw.slice(eqIdx + 1));
      const parsed = JSON.parse(decoded) as unknown;
      if (
        typeof parsed !== "object" ||
        parsed === null ||
        !("_v" in parsed) ||
        (parsed as { _v: unknown })._v !== COOKIE_VERSION ||
        !("categories" in parsed) ||
        typeof (parsed as { categories: unknown }).categories !== "object"
      ) {
        return null;
      }
      return parsed as ConsentCookieState;
    } catch {
      return null;
    }
  }
  return null;
}

export function writeConsentCookie(state: ConsentCookieState): void {
  if (typeof document === "undefined") return;
  const encoded = encodeURIComponent(JSON.stringify(state));
  document.cookie = `${CONSENT_COOKIE_NAME}=${encoded}; SameSite=Lax; Secure; Max-Age=${ONE_YEAR_SECONDS}; Path=/`;
}

export function clearConsentCookie(): void {
  if (typeof document === "undefined") return;
  document.cookie = `${CONSENT_COOKIE_NAME}=; Max-Age=0; Path=/`;
}
