/**
 * Server-side date utilities for Google Search Console
 * Prevents LLM date hallucination by handling all date calculations server-side
 */

/**
 * Format a Date object as YYYY-MM-DD
 */
export function formatDate(date: Date): string {
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  return `${year}-${month}-${day}`;
}

/**
 * Get a date range ending yesterday, spanning N days
 * GSC data is typically 2-3 days delayed, so we end at yesterday
 */
export function getDateRange(days: number): { startDate: string; endDate: string } {
  const endDate = new Date();
  endDate.setDate(endDate.getDate() - 1); // Yesterday
  
  const startDate = new Date(endDate);
  startDate.setDate(startDate.getDate() - days + 1);
  
  return {
    startDate: formatDate(startDate),
    endDate: formatDate(endDate)
  };
}

/**
 * Parse and resolve date range from various input formats
 * Priority: explicit dates > relative days > default 28 days
 */
export function parseDateRange(
  startDate?: string,
  endDate?: string,
  days?: number
): { startDate: string; endDate: string } {
  // If both dates provided, validate and return
  if (startDate && endDate) {
    const start = new Date(startDate);
    const end = new Date(endDate);
    
    if (isNaN(start.getTime()) || isNaN(end.getTime())) {
      throw new Error('Invalid date format. Use YYYY-MM-DD');
    }
    
    if (start > end) {
      throw new Error('startDate must be before or equal to endDate');
    }
    
    return { startDate, endDate };
  }
  
  // If only days provided, use relative range
  if (days) {
    if (days < 1 || days > 16) {
      throw new Error('days must be between 1 and 16 months (480 days)');
    }
    return getDateRange(days);
  }
  
  // Default: last 28 days
  return getDateRange(28);
}

/**
 * Validate that a date string is in YYYY-MM-DD format
 */
export function isValidDateString(dateStr: string): boolean {
  const regex = /^\d{4}-\d{2}-\d{2}$/;
  if (!regex.test(dateStr)) return false;
  
  const date = new Date(dateStr);
  return !isNaN(date.getTime());
}

/**
 * Get date N days ago from today
 */
export function getDaysAgo(days: number): string {
  const date = new Date();
  date.setDate(date.getDate() - days);
  return formatDate(date);
}

/**
 * Calculate number of days between two dates
 */
export function daysBetween(startDate: string, endDate: string): number {
  const start = new Date(startDate);
  const end = new Date(endDate);
  const diffTime = Math.abs(end.getTime() - start.getTime());
  return Math.ceil(diffTime / (1000 * 60 * 60 * 24));
}
