import Cookies from "js-cookie";

const TOKEN_KEY = "auth_token"; // cookie nomi
const REF_TOKEN_KEY = "ref_auth_token"; // cookie nomi
const EXPIRE_DAYS = 1; // token necha kun saqlansin
const REF_EXPIRE_DAYS = 30; // token necha kun saqlansin

/**
 * Tokenni cookie'ga saqlaydi
 * @param token - foydalanuvchining JWT tokeni
 */
export const setAuthToken = (token: string) => {
  Cookies.set(TOKEN_KEY, token, {
    expires: EXPIRE_DAYS,
    secure: true, // faqat https da ishlaydi
    sameSite: "strict", // CSRF xavfsizligi
  });
};

export const setAuthRefToken = (token: string) => {
  Cookies.set(REF_TOKEN_KEY, token, {
    expires: REF_EXPIRE_DAYS,
    secure: true, // faqat https da ishlaydi
    sameSite: "strict", // CSRF xavfsizligi
  });
};

/**
 * Cookie'dan tokenni oladi
 * @returns string | undefined
 */
export const getAuthToken = (): string | undefined => {
  return Cookies.get(TOKEN_KEY);
};

export const getRefAuthToken = (): string | undefined => {
  return Cookies.get(REF_TOKEN_KEY);
};

/**
 * Tokenni cookie'dan o‘chiradi
 */
export const removeAuthToken = () => {
  Cookies.remove(TOKEN_KEY);
};

export const removeRefAuthToken = () => {
  Cookies.remove(REF_TOKEN_KEY);
};

/**
 * Foydalanuvchi tizimga kirgan yoki yo‘qligini tekshiradi
 * @returns boolean
 */
export const isAuthenticated = (): boolean => {
  return !!Cookies.get(TOKEN_KEY);
};
