/**
 * The adjustDecimals function rounds a numerical value to a specified number of
 * decimal places, retaining the original formatting for values with fewer decimals
 * and preserving very small values in their entirety.
 *
 * Note: not to be used for calculations, only for display purposes
 */
import { intlNumberFormatter } from "./intlNumberFormatter";

export function adjustDecimals(
	value: number | string,
	decimals = 2,
	locale = "en-US",
): string {
	const formatter = intlNumberFormatter(locale);

	const _value = Number(value);

	// Handle very small values or zero
	if (Math.abs(_value) < 10 ** -decimals || _value === 0) {
		const valueString = value.toString();
		const decimalPart = valueString.includes(".") ? [...valueString.split(".")[1]] : [];
		// Convert the decimal part into an array of characters

		const decimalPartArray = Array.from(decimalPart).entries();

		const decimalPartToShow = [];
		let foundFirstNonZero = false;

		for (const [index, item] of decimalPartArray) {
			// Always add zeros until the first non-zero is found
			if (!foundFirstNonZero) {
				decimalPartToShow.push(item);
				if (item !== "0") {
					foundFirstNonZero = true; // Mark that we've found the first non-zero digit
				}
			} else {
				// After the first non-zero, continue adding digits until we reach the specified decimals
				if (decimalPartToShow.length < decimals) {
					decimalPartToShow.push(item);
				} else {
					break; // Stop if we've reached the specified number of decimal places
				}
			}
		}

		const integer = valueString.split(".")[0];
		// Join the decimal part and remove any trailing zeros
		const decimalResult = decimalPartToShow.join("").replace(/0+$/, '');
		return decimalResult ? `${integer}.${decimalResult}` : `${integer}`; // Return the formatted number
	}

	// Round to the specified number of decimals
	const roundedValue = _value.toFixed(decimals);

	// Remove trailing zeros and unnecessary decimal point
	return formatter.format(Number(Number(roundedValue).toString()));
}

// Test cases
// const locale = "en-US";
// console.log(adjustDecimals(0.000608213999999996, 2, locale)); // "0.0006"
// console.log(adjustDecimals(0.0608213999999996, 4, locale)); // "0.06"
// console.log(adjustDecimals(1.000001, 2, locale)); // "1"
// console.log(adjustDecimals(0.000001, 2, locale)); // "0.000001"
// console.log(adjustDecimals(100.38300001, 2, locale)); // "100.38"
// console.log(adjustDecimals(0.001, 2, locale)); // "0.001"
// console.log(adjustDecimals(0.00001, 2, locale)); // "0.00001"
// console.log(adjustDecimals(0.50001, 2, locale)); // "0.50"
// console.log(adjustDecimals(46.38393, 2, locale)); // "46.39"
