import { isValid, parse, parseISO } from 'date-fns';
import { formatDate } from '@/lib/date-format';
import { formatNumber } from '@/lib/number-format';

function coerceDate(value: string | Date | null | undefined) {
  if (!value) {
    return null;
  }

  if (value instanceof Date) {
    return isValid(value) ? value : null;
  }

  if (/^\d{4}-\d{2}-\d{2}$/.test(value)) {
    const parsed = parse(value, 'yyyy-MM-dd', new Date());
    return isValid(parsed) ? parsed : null;
  }

  const isoParsed = parseISO(value);
  return isValid(isoParsed) ? isoParsed : null;
}

export function formatCrmDate(value: string | Date | null | undefined) {
  const date = coerceDate(value);
  return date ? formatDate(date) : '';
}

export function formatCrmNumber(
  value: number | string | null | undefined,
  options?: Intl.NumberFormatOptions
) {
  return formatNumber(value, options);
}

export function sanitizeDecimalInput(value: string) {
  const normalized = value.replaceAll(',', '').replace(/[^\d.-]/g, '');
  const [head = '', ...tail] = normalized.split('.');
  const integerPart = head.replace(/(?!^)-/g, '');
  const decimalPart = tail.join('');
  return decimalPart.length > 0 ? `${integerPart}.${decimalPart}` : integerPart;
}
