import type { StorefrontProductCard } from "@/types/storefront";

function parseLocalizedPrice(value?: string) {
  if (!value) {
    return null;
  }

  const numeric = value.replace(/[^\d,.-]/g, "").trim();

  if (!numeric) {
    return null;
  }

  const normalized = numeric.includes(",")
    ? numeric.replace(/\./g, "").replace(",", ".")
    : numeric;

  const amount = Number.parseFloat(normalized);

  return Number.isFinite(amount) ? amount : null;
}

export function getProductDiscountPercent(product: Pick<StorefrontProductCard, "isOnSale" | "regularPrice" | "salePrice">) {
  if (!product.isOnSale || !product.salePrice || !product.regularPrice) {
    return null;
  }

  const regular = parseLocalizedPrice(product.regularPrice);
  const sale = parseLocalizedPrice(product.salePrice);

  if (regular === null || sale === null || regular <= 0 || sale >= regular) {
    return null;
  }

  return Math.round(((regular - sale) / regular) * 100);
}

export function getProductDiscountLabel(product: Pick<StorefrontProductCard, "isOnSale" | "regularPrice" | "salePrice">) {
  const percent = getProductDiscountPercent(product);

  if (percent === null || percent <= 0) {
    return null;
  }

  return `-${percent}%`;
}

export function hasRealProductDiscount(product: Pick<StorefrontProductCard, "isOnSale" | "regularPrice" | "salePrice">) {
  return getProductDiscountPercent(product) !== null;
}
