const DEFAULT_PATH = "/";
const SEVEN_DAYS_IN_SECONDS = 60 * 60 * 24 * 7;

export const AUTH_TOKEN_COOKIE = "auth-token";
export const REFRESH_TOKEN_COOKIE = "refresh-token";
export const AUTH_USER_COOKIE = "auth-user";

export const AUTH_COOKIE_MAX_AGE = SEVEN_DAYS_IN_SECONDS;

export const getCookie = (name: string) => {
  const match = document.cookie
    .split("; ")
    .find((entry) => entry.startsWith(`${name}=`));

  return match ? decodeURIComponent(match.split("=").slice(1).join("=")) : null;
};

export const setCookie = (
  name: string,
  value: string,
  maxAge = AUTH_COOKIE_MAX_AGE,
) => {
  document.cookie = `${name}=${encodeURIComponent(value)}; Max-Age=${maxAge}; path=${DEFAULT_PATH}; SameSite=Lax`;
};

export const clearCookie = (name: string) => {
  document.cookie = `${name}=; Max-Age=0; path=${DEFAULT_PATH}`;
};

export const clearSessionCookies = () => {
  [
    AUTH_TOKEN_COOKIE,
    REFRESH_TOKEN_COOKIE,
    AUTH_USER_COOKIE,
    "current-position-id",
    "selected-position-id",
  ].forEach(clearCookie);
};
