/**
 * Fracción arancelaria mexicana: 8 dígitos de fracción + 2 de NICO (10 sin puntos).
 */

export type MexTariffCatalogRow = {
	fraction?: string | null;
	nico?: string | null;
	code?: string | null;
};

function digitsOnly(s: string): string {
	return s.replace(/\D/g, '');
}

/** 10 dígitos: base (8) + NICO (2), sin puntos. */
export function buildMexTariffDigitsFromCatalogRow(tf: MexTariffCatalogRow): string {
	const fromFraction = String(tf.fraction ?? '')
		.replace(/\./g, '')
		.replace(/\D/g, '');
	const fromCode = digitsOnly(String(tf.code ?? ''));
	let base8 = fromFraction.slice(0, 8);
	if (base8.length === 0) base8 = fromCode.slice(0, 8);
	if (base8.length < 8) base8 = base8.padEnd(8, '0');

	const nico2 = digitsOnly(String(tf.nico ?? '')).slice(-2).padStart(2, '0');
	return `${base8}${nico2}`.slice(0, 10);
}

export function splitMexTariffDigitsForSitar(digitsOrLegacy: string | null | undefined): {
	fraccion8: string;
	nico2: string;
} {
	const raw = String(digitsOrLegacy ?? '').replace(/\./g, '').replace(/\D/g, '');
	const fraccion8 = raw.slice(0, 8).padEnd(8, '0');
	const nico2 = (raw.length >= 10 ? raw.slice(8, 10) : '00').padStart(2, '0');
	return { fraccion8, nico2: nico2.slice(0, 2) };
}

/**
 * Formato de vista: 8 → XXXX.XX.XX, 10 → XXXX.XX.XX.NN.
 * Si ya contiene puntos, se devuelve igual (datos legados).
 */
export function formatMexTariffDigitsForDisplay(value: string | null | undefined): string {
	const frac = String(value ?? '').trim();
	if (!frac) return '';
	if (frac.includes('.')) return frac;
	const digits = frac.replace(/\D/g, '');
	if (digits.length === 8) {
		return `${digits.slice(0, 4)}.${digits.slice(4, 6)}.${digits.slice(6, 8)}`;
	}
	if (digits.length === 10) {
		return `${digits.slice(0, 4)}.${digits.slice(4, 6)}.${digits.slice(6, 8)}.${digits.slice(8, 10)}`;
	}
	return frac;
}

/** Migra valor legado (puntos o 8 dígitos) a 10 dígitos sin puntos. */
export function normalizeMexTariffDigitsStored(raw: string | null | undefined): string {
	const d = String(raw ?? '').replace(/\D/g, '');
	if (!d) return '';
	if (d.length >= 10) return d.slice(0, 10);
	if (d.length === 8) return `${d}00`;
	return d.padEnd(10, '0').slice(0, 10);
}
