const CHATBOT_SESSION_ID_COOKIE = "chatbot_session_id";

export const getCookie = (name: string): string | null => {
  if (typeof document === "undefined") return null;

  const value = `; ${document.cookie}`;
  const parts = value.split(`; ${name}=`);

  if (parts.length === 2) {
    return parts.pop()?.split(";").shift() || null;
  }

  return null;
};

export const setCookie = (
  name: string,
  value: string,
  days: number = 365
): void => {
  if (typeof document === "undefined") return;

  const date = new Date();
  date.setTime(date.getTime() + days * 24 * 60 * 60 * 1000);
  const expires = `expires=${date.toUTCString()}`;
  document.cookie = `${name}=${value};${expires};path=/;SameSite=Lax`;
};

export const getChatbotSessionId = (): string | null => {
  return getCookie(CHATBOT_SESSION_ID_COOKIE);
};

export const setChatbotSessionId = (sessionId: string): void => {
  setCookie(CHATBOT_SESSION_ID_COOKIE, sessionId);
};
