/**
 * Utility for date formatting and conversion.
 * Canonical API format: DD/MM/YYYY
 * Native input[type="date"] format: YYYY-MM-DD
 */

/**
 * Converts DD/MM/YYYY or YYYYMMDD to YYYY-MM-DD for native date input.
 */
export function toInputDate(dateStr: string | number | null | undefined): string {
	if (!dateStr) return '';

	const str = String(dateStr);

	if (/^\d{8}$/.test(str)) {
		const y = str.substring(0, 4);
		const m = str.substring(4, 6);
		const d = str.substring(6, 8);
		return `${y}-${m}-${d}`;
	}

	if (/^\d{2}\/\d{2}\/\d{4}$/.test(str)) {
		const [d, m, y] = str.split('/');
		return `${y}-${m}-${d}`;
	}

	if (/^\d{4}-\d{2}-\d{2}$/.test(str)) {
		return str;
	}

	return '';
}

/**
 * Converts YYYY-MM-DD or YYYYMMDD to DD/MM/YYYY for API.
 */
export function toDbDate(dateStr: string | null | undefined): string | null {
	if (!dateStr) return null;

	if (/^\d{2}\/\d{2}\/\d{4}$/.test(dateStr)) {
		return dateStr;
	}

	if (/^\d{4}-\d{2}-\d{2}$/.test(dateStr)) {
		const [y, m, d] = dateStr.split('-');
		return `${d}/${m}/${y}`;
	}

	if (/^\d{8}$/.test(dateStr)) {
		const y = dateStr.substring(0, 4);
		const m = dateStr.substring(4, 6);
		const d = dateStr.substring(6, 8);
		return `${d}/${m}/${y}`;
	}

	return null;
}
