// Duration validation and parsing utilities
// Converts various duration formats to minutes and back

/**
 * Parse duration string to minutes
 * Supports: "2 saat", "3 hours", "90 dakika", "120 minutes", "2h", "90m"
 */
export const parseDuration = (duration: string): number => {
  if (!duration) return 120; // default 2 saat
  
  const normalized = duration.toLowerCase().trim();
  
  // Match patterns: "2 saat", "3 hours", "90 dakika", "120 minutes", "2h", "90m"
  const match = normalized.match(/(\d+(?:\.\d+)?)\s*(saat|hour|h|dakika|minute|min|m)/i);
  
  if (!match) return 120; // default 2 saat
  
  const value = parseFloat(match[1]);
  const unit = match[2].toLowerCase();
  
  // Convert to minutes
  if (unit.includes('saat') || unit.includes('hour') || unit === 'h') {
    return Math.round(value * 60);
  }
  
  // Already in minutes
  return Math.round(value);
};

/**
 * Format minutes to human-readable duration string (Turkish)
 */
export const formatDuration = (minutes: number): string => {
  if (minutes < 60) {
    return `${minutes} dakika`;
  }
  
  const hours = Math.floor(minutes / 60);
  const mins = minutes % 60;
  
  if (mins === 0) {
    return `${hours} saat`;
  }
  
  return `${hours} saat ${mins} dakika`;
};

/**
 * Validate duration string format
 */
export const isValidDuration = (duration: string): boolean => {
  if (!duration) return false;
  
  const normalized = duration.toLowerCase().trim();
  const match = normalized.match(/(\d+(?:\.\d+)?)\s*(saat|hour|h|dakika|minute|min|m)/i);
  
  return match !== null;
};

/**
 * Normalize duration to standard format (e.g., "2 saat", "90 dakika")
 */
export const normalizeDuration = (duration: string): string => {
  const minutes = parseDuration(duration);
  return formatDuration(minutes);
};
