import i18n from "@/shared/config/i18n";
import { LanguageRoutes } from "@/shared/config/i18n/type";

/**
 * Format price. With label.
 * @param amount Price
 * @param withLabel Show label. Default false
 * @returns string. Ex. 1 000 000 so‘m
 */
const formatPrice = (amount: number | string, withLabel = false): string => {
  const locale = i18n.language;
  const label = withLabel
    ? locale === LanguageRoutes.RU
      ? " сум"
      : locale === LanguageRoutes.UZ
        ? " so‘m"
        : " so‘m"
    : "";

  // Agar qiymat bo‘sh yoki null/undefined bo‘lsa — hech narsa ko‘rsatmaymiz
  if (amount === "" || amount === null || amount === undefined) return "";

  // Faqat raqamlarni qoldiramiz
  const numeric = String(amount).replace(/\D/g, "");

  // Agar hech qanday raqam kiritilmagan bo‘lsa, bo‘sh qaytaramiz
  if (numeric === "") return "";

  // Raqamni 3 xonadan ajratamiz
  const formatted = numeric.replace(/\B(?=(\d{3})+(?!\d))/g, " ");

  return formatted + label;
};

export default formatPrice;
