import Cookies from "js-cookie";

type CookieOptions = NonNullable<Parameters<typeof Cookies.set>[2]>;

const REMEMBER_ME_STORAGE_KEY = "rememberMe";

const parseRememberMe = (value: string | null) => {
  if (!value) return false;

  try {
    return JSON.parse(value) === true;
  } catch {
    return false;
  }
};

export const getRememberMePreference = () =>
  parseRememberMe(localStorage.getItem(REMEMBER_ME_STORAGE_KEY));

export const persistRememberMePreference = (rememberMe: boolean) => {
  localStorage.setItem(REMEMBER_ME_STORAGE_KEY, JSON.stringify(rememberMe));
};

export const clearRememberMePreference = () => {
  localStorage.removeItem(REMEMBER_ME_STORAGE_KEY);
};

export const getAuthCookieOptions = (
  rememberMe: boolean,
): CookieOptions => ({
  ...(rememberMe ? { expires: 7 } : {}),
  secure: window.location.protocol === "https:",
  sameSite: "Strict",
});

export const setAuthCookies = ({
  token,
  refreshToken,
  rememberMe,
}: {
  token: string;
  refreshToken: string;
  rememberMe: boolean;
}) => {
  const cookieOptions = getAuthCookieOptions(rememberMe);

  Cookies.set("auth-token", token, cookieOptions);
  Cookies.set("refresh-token", refreshToken, cookieOptions);
};
