import type { Pedimento } from '$lib/api/dashboard/a76/pedimentos';
import type { DodaPedimento, DodaPedimentoCreate } from '$lib/api/dashboard/a76/general_catalogs/doda';

export type PedimentoDetailRow = DodaPedimentoCreate & { id?: number; pedimento_line?: number };

/**
 * Misma convención que digitalización: AA-Patente-Pedimento
 */
export function buildPedimentoLabel(pedimento: Pedimento): string {
	return `${pedimento.customs_office?.slice(0, 2) || ''}-${pedimento.license || ''}-${pedimento.pedimento_number || ''}`.replace(
		/^-+|-+$/g,
		''
	);
}

export function yyyymmddTodayInt(): number {
	const d = new Date();
	const y = d.getFullYear();
	const m = String(d.getMonth() + 1).padStart(2, '0');
	const day = String(d.getDate()).padStart(2, '0');
	return Number(`${y}${m}${day}`);
}

/**
 * Sincroniza el campo `shipments` a partir de remesas en detalle (coma-separado).
 */
export function syncShipmentsFromPedimentos(
	detail: Array<Pick<DodaPedimento | PedimentoDetailRow, 'shipment'>>
): string {
	const parts: string[] = [];
	for (const p of detail) {
		const s = (p.shipment || '').toString().trim();
		if (s && !parts.includes(s)) parts.push(s);
	}
	return parts.join(', ');
}

/**
 * Une etiquetas y números de documento al campo legado `pedimentos`.
 */
export function appendPedimentosString(
	current: string | undefined,
	segment: string
): string {
	const next = (segment || '').trim();
	if (!next) return current || '';
	const cur = (current || '').trim();
	if (!cur) return next;
	if (cur.split(/[;,]/).map((s) => s.trim()).includes(next)) return cur;
	return `${cur}; ${next}`;
}

export function pedimentoRowFromCatalog(
	p: Pedimento,
	authorizationPatent: string
): { row: DodaPedimentoCreate; label: string } {
	const document =
		(p.pedimento_number && String(p.pedimento_number)) ||
		buildPedimentoLabel(p) ||
		'';
	return {
		row: {
			authorization_patent: (authorizationPatent || p.license || '').trim() || undefined,
			document: document
		},
		label: buildPedimentoLabel(p)
	};
}

/** `customs_clearance === 1` = PITA (legacy DespachoAduanero '3'): no aplica catálogo de tipo americano. */
export function isPitaCustomsClearance(customsClearance: number | undefined | null): boolean {
	return customsClearance === 1;
}

/** Códigos de error para mapear a i18n (`sidebar.doda_form.*`). */
export type AmericanPedimentoTipoError = 'required' | 'import_range' | 'export_range' | 'op_undefined';

/**
 * Valida `american_pedimento_type` frente a `operation_type` (legacy Clarion).
 * Importación: tipos 1–5. Exportación: tipos 6–8.
 */
export function validateAmericanPedimentoTipo(
	operationType: string | undefined,
	tipo: string | undefined
): AmericanPedimentoTipoError | null {
	const t = (tipo || '').trim();
	if (!t) return 'required';

	const op = (operationType || '').trim().toUpperCase();
	const isImport = op === 'I' || op === '1';
	const isExport = op === 'E' || op === '2';

	if (isImport) {
		if (!['1', '2', '3', '4', '5'].includes(t)) {
			return 'import_range';
		}
	} else if (isExport) {
		if (!['6', '7', '8'].includes(t)) {
			return 'export_range';
		}
	} else {
		return 'op_undefined';
	}
	return null;
}
