import { useMemo } from "react";
import { PercentageDTO } from "../../common";

/**
 * Hook para porcentajes escalados (value+scale).
 */
export function usePercentage() {
  const toNumber = (p?: PercentageDTO | null): number => {
    if (!p?.value || !p.scale) return 0;
    return Number(p.value) / 10 ** Number(p.scale);
  };

  const fromNumber = (num: number, scale = 2): PercentageDTO => ({
    value: Math.round(num * 10 ** scale).toString(),
    scale: scale.toString(),
  });

  const format = (p: PercentageDTO): string =>
    `${toNumber(p).toLocaleString(undefined, {
      minimumFractionDigits: 2,
      maximumFractionDigits: 2,
    })}%`;

  // biome-ignore lint/correctness/useExhaustiveDependencies: <explanation>
  return useMemo(() => ({ toNumber, fromNumber, format }), []);
}
