export function isEmail(input: string): boolean {
  const emailRegex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
  return emailRegex.test(input);
}

export function NumberFormat(number: number): string {
  return Intl.NumberFormat("fa-IR").format(number);
}

export const getToken = () => {
  return localStorage.getItem(import.meta.env.VITE_TOKEN_NAME);
};

export const getRefreshToken = () => {
  return localStorage.getItem(import.meta.env.VITE_REFRESH_TOKEN_NAME);
};

export const setToken = (token: string) => {
  localStorage.setItem(import.meta.env.VITE_TOKEN_NAME, token);
};

export const setRefreshToken = (refreshToken: string) => {
  localStorage.setItem(import.meta.env.VITE_REFRESH_TOKEN_NAME, refreshToken);
};

export const removeToken = () => {
  localStorage.removeItem(import.meta.env.VITE_TOKEN_NAME);
};

export const removeRefreshToken = () => {
  localStorage.removeItem(import.meta.env.VITE_REFRESH_TOKEN_NAME);
};

export const timeAgo = (date: string | Date): string => {
  const now = new Date();
  const past = new Date(date);
  const diff = Math.floor((now.getTime() - past.getTime()) / 1000); // اختلاف بر حسب ثانیه

  const units = [
    { name: "سال", value: 60 * 60 * 24 * 365 },
    { name: "ماه", value: 60 * 60 * 24 * 30 },
    { name: "روز", value: 60 * 60 * 24 },
    { name: "ساعت", value: 60 * 60 },
    { name: "دقیقه", value: 60 },
    { name: "ثانیه", value: 1 },
  ];

  for (const unit of units) {
    const amount = Math.floor(diff / unit.value);
    if (amount >= 1) return `${amount} ${unit.name} پیش`;
  }

  return "همین الان";
};

export interface IGeneralError {
  status: number;
  success: boolean;
  error: {
    message: string[];
  };
}

export const extractErrorMessage = (
  error: Error | unknown,
  fallbackMessage: string = "خطایی رخ داده است"
): string => {
  try {
    const axiosError = error as { response?: { data: IGeneralError } };
    return axiosError?.response?.data?.error?.message?.[0] || fallbackMessage;
  } catch {
    return fallbackMessage;
  }
};
