/**
 * Formatting utility functions for Detailed Reports
 */

import { formatHoursMinutes } from '@/utils/slaTracker';

/**
 * Format TAT hours (working hours to working days)
 * Backend returns working hours, so we divide by 8 (working hours per day) not 24
 */
export function formatTAT(hours: number | null | undefined): string {
  if (!hours && hours !== 0) return 'N/A';
  const WORKING_HOURS_PER_DAY = 8;
  if (hours < WORKING_HOURS_PER_DAY) return formatHoursMinutes(hours);
  const days = Math.floor(hours / WORKING_HOURS_PER_DAY);
  const remainingHours = hours % WORKING_HOURS_PER_DAY;
  return remainingHours > 0 ? `${days}d ${formatHoursMinutes(remainingHours)}` : `${days}d`;
}

/**
 * Format date for display
 */
export function formatDate(date: string | null | undefined): string {
  if (!date) return 'N/A';
  try {
    const d = new Date(date);
    return d.toLocaleDateString('en-US', {
      year: 'numeric',
      month: 'short',
      day: 'numeric',
      hour: '2-digit',
      minute: '2-digit',
    });
  } catch {
    return date;
  }
}

/**
 * Format date for CSV export (no commas, consistent format)
 */
export function formatDateForCSV(date: string | null | undefined): string {
  if (!date) return 'N/A';
  try {
    const d = new Date(date);
    // Format: YYYY-MM-DD HH:MM (no commas, Excel-friendly)
    const year = d.getFullYear();
    const month = String(d.getMonth() + 1).padStart(2, '0');
    const day = String(d.getDate()).padStart(2, '0');
    const hours = String(d.getHours()).padStart(2, '0');
    const minutes = String(d.getMinutes()).padStart(2, '0');
    return `${year}-${month}-${day} ${hours}:${minutes}`;
  } catch {
    return date;
  }
}

/**
 * Map activity type to display label
 */
export function mapActivityType(type: string, _activityDescription?: string): string {
  const typeLower = (type || '').toLowerCase();
  if (typeLower.includes('created') || typeLower.includes('create')) return 'Created Request';
  if (typeLower.includes('approval') || typeLower.includes('approved')) return 'Approved Request';
  if (typeLower.includes('rejection') || typeLower.includes('rejected')) return 'Rejected Request';
  if (typeLower.includes('comment')) return 'Added Comment';
  if (typeLower.includes('view') || typeLower.includes('viewed')) return 'Viewed Request';
  if (typeLower.includes('upload') || typeLower.includes('document')) return 'Uploaded Document';
  if (typeLower.includes('login')) return 'Login';
  return type || 'Activity';
}

