// src/features/flyer/dateUtils.ts
import { parseISO, format, isValid, differenceInDays } from 'date-fns';

export const formatShortDate = (dateString: string | null | undefined): string | null => {
  if (!dateString) return null;
  // Using `parseISO` from date-fns is more reliable than `new Date()` for YYYY-MM-DD strings.
  // It correctly interprets the string as a local date, avoiding timezone-related "off-by-one" errors.
  const date = parseISO(dateString);
  if (isValid(date)) {
    return format(date, 'MMM d');
  }
  return null;
};

export const calculateDaysBetween = (
  startDate: string | Date | null | undefined,
  endDate: string | Date | null | undefined,
): number | null => {
  if (!startDate || !endDate) return null;

  const start = typeof startDate === 'string' ? parseISO(startDate) : startDate;
  const end = typeof endDate === 'string' ? parseISO(endDate) : endDate;

  if (!isValid(start) || !isValid(end)) return null;

  return differenceInDays(end, start);
};

interface DateRangeOptions {
  verbose?: boolean;
}

export const formatDateRange = (
  startDate: string | null | undefined,
  endDate: string | null | undefined,
  options?: DateRangeOptions,
): string | null => {
  if (!options?.verbose) {
    const start = formatShortDate(startDate);
    const end = formatShortDate(endDate);

    if (start && end) {
      return start === end ? start : `${start} - ${end}`;
    }
    return start || end || null;
  }

  // Verbose format logic
  const dateFormat = 'MMMM d, yyyy';
  const formatFn = (dateStr: string | null | undefined) => {
    if (!dateStr) return null;
    const date = parseISO(dateStr);
    return isValid(date) ? format(date, dateFormat) : null;
  };

  const start = formatFn(startDate);
  const end = formatFn(endDate);

  if (start && end) {
    return start === end ? `Valid on ${start}` : `Deals valid from ${start} to ${end}`;
  }
  if (start) return `Deals start ${start}`;
  if (end) return `Deals end ${end}`;
  return null;
};
