import {
  ADMIN_TOKEN_COOKIE_MAX_AGE_SECONDS,
  ADMIN_TOKEN_STORAGE_KEY,
} from "@/lib/admin-token-constants";

export function readAdminTokenFromCookieString(
  cookieHeader: string | null | undefined,
): string | null {
  if (!cookieHeader) {
    return null;
  }

  const prefix = `${ADMIN_TOKEN_STORAGE_KEY}=`;
  for (const part of cookieHeader.split(";")) {
    const trimmed = part.trim();
    if (!trimmed.startsWith(prefix)) {
      continue;
    }
    const raw = trimmed.slice(prefix.length);
    if (!raw) {
      return null;
    }
    try {
      const decoded = decodeURIComponent(raw).trim();
      return decoded !== "" ? decoded : null;
    } catch {
      return null;
    }
  }

  return null;
}

export function readAdminTokenFromDocumentCookie(): string | null {
  if (typeof document === "undefined") {
    return null;
  }

  return readAdminTokenFromCookieString(document.cookie);
}

export function writeAdminTokenCookie(token: string | null): void {
  if (typeof document === "undefined") {
    return;
  }

  const secure =
    typeof window !== "undefined" && window.location.protocol === "https:";
  const base = `path=/; SameSite=Lax`;

  if (!token || token.trim() === "") {
    document.cookie = `${ADMIN_TOKEN_STORAGE_KEY}=; ${base}; max-age=0`;
    return;
  }

  const value = encodeURIComponent(token.trim());
  const maxAge = `max-age=${ADMIN_TOKEN_COOKIE_MAX_AGE_SECONDS}`;
  document.cookie = `${ADMIN_TOKEN_STORAGE_KEY}=${value}; ${base}; ${maxAge}${
    secure ? "; Secure" : ""
  }`;
}
