// Date/Time Helper Utilities
// Using date-fns for consistent date handling

import { format, parseISO, isValid, addDays, subDays, differenceInDays } from 'date-fns';

/**
 * Format date to ISO string
 */
export function formatDate(date: Date | string): string {
  const dateObj = typeof date === 'string' ? parseISO(date) : date;
  if (!isValid(dateObj)) {
    throw new Error('Invalid date');
  }
  return format(dateObj, "yyyy-MM-dd'T'HH:mm:ss.SSSxxx");
}

/**
 * Parse date string to Date object
 */
export function parseDate(dateString: string): Date {
  const date = parseISO(dateString);
  if (!isValid(date)) {
    throw new Error(`Invalid date string: ${dateString}`);
  }
  return date;
}

/**
 * Add days to a date
 */
export function addDaysToDate(date: Date | string, days: number): Date {
  const dateObj = typeof date === 'string' ? parseISO(date) : date;
  if (!isValid(dateObj)) {
    throw new Error('Invalid date');
  }
  return addDays(dateObj, days);
}

/**
 * Subtract days from a date
 */
export function subtractDaysFromDate(date: Date | string, days: number): Date {
  const dateObj = typeof date === 'string' ? parseISO(date) : date;
  if (!isValid(dateObj)) {
    throw new Error('Invalid date');
  }
  return subDays(dateObj, days);
}

/**
 * Calculate days difference between two dates
 */
export function daysDifference(date1: Date | string, date2: Date | string): number {
  const date1Obj = typeof date1 === 'string' ? parseISO(date1) : date1;
  const date2Obj = typeof date2 === 'string' ? parseISO(date2) : date2;
  
  if (!isValid(date1Obj) || !isValid(date2Obj)) {
    throw new Error('Invalid date');
  }
  
  return differenceInDays(date1Obj, date2Obj);
}

/**
 * Check if date is in the past
 */
export function isPastDate(date: Date | string): boolean {
  const dateObj = typeof date === 'string' ? parseISO(date) : date;
  if (!isValid(dateObj)) {
    throw new Error('Invalid date');
  }
  return dateObj < new Date();
}

/**
 * Check if date is in the future
 */
export function isFutureDate(date: Date | string): boolean {
  const dateObj = typeof date === 'string' ? parseISO(date) : date;
  if (!isValid(dateObj)) {
    throw new Error('Invalid date');
  }
  return dateObj > new Date();
}

