/**
 * Dashboard export utility functions
 * Handles CSV exports for dashboard data
 */

import { ApproverPerformance, DateRange } from '@/services/dashboard.service';
import { dashboardService } from '@/services/dashboard.service';
import { formatHoursMinutes } from '@/utils/slaTracker';

/**
 * Export Approver Performance data to CSV
 */
export async function exportApproverPerformanceToCSV(
  dateRange: DateRange,
  customStartDate?: Date,
  customEndDate?: Date
): Promise<void> {
  // Fetch all approver performance data (no pagination)
  const allData: ApproverPerformance[] = [];
  let currentPage = 1;
  let hasMore = true;
  const maxPages = 100; // Safety limit
  
  while (hasMore && currentPage <= maxPages) {
    const result = await dashboardService.getApproverPerformance(
      dateRange,
      currentPage,
      100, // Large page size
      customStartDate,
      customEndDate
    );
    
    if (result.performance && result.performance.length > 0) {
      allData.push(...result.performance);
      currentPage++;
      hasMore = currentPage <= result.pagination.totalPages;
    } else {
      hasMore = false;
    }
  }
  
  // Convert to CSV format
  const csvRows = [
    ['Approver Name', 'Total Approved', 'TAT Compliance (%)', 'Avg Response Time', 'Pending Count'].join(',')
  ];
  
  allData.forEach((approver) => {
    const row = [
      `"${(approver.approverName || 'Unknown').replace(/"/g, '""')}"`,
      approver.totalApproved || 0,
      approver.tatCompliancePercent || 0,
      formatHoursMinutes(approver.avgResponseHours),
      approver.pendingCount || 0
    ];
    csvRows.push(row.join(','));
  });
  
  const csvContent = csvRows.join('\n');
  const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
  const link = document.createElement('a');
  const url = URL.createObjectURL(blob);
  link.setAttribute('href', url);
  link.setAttribute('download', `approver-performance-report-${new Date().toISOString().split('T')[0]}.csv`);
  link.style.visibility = 'hidden';
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);
  URL.revokeObjectURL(url);
}

/**
 * Export Department Stats data to CSV
 */
export async function exportDepartmentStatsToCSV(
  dateRange: DateRange,
  customStartDate?: Date,
  customEndDate?: Date
): Promise<void> {
  // Get all department stats
  const allDeptStats = await dashboardService.getDepartmentStats(dateRange, customStartDate, customEndDate);
  
  const csvRows = [
    ['Department', 'Total Requests', 'Approved', 'Rejected', 'In Progress', 'Approval Rate (%)'].join(',')
  ];
  
  allDeptStats.forEach((dept: any) => {
    const row = [
      `"${(dept.department || 'Unknown').replace(/"/g, '""')}"`,
      dept.totalRequests || 0,
      dept.approved || 0,
      dept.rejected || 0,
      dept.inProgress || 0,
      dept.approvalRate || 0
    ];
    csvRows.push(row.join(','));
  });
  
  const csvContent = csvRows.join('\n');
  const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
  const link = document.createElement('a');
  const url = URL.createObjectURL(blob);
  link.setAttribute('href', url);
  link.setAttribute('download', `department-workflow-summary-${new Date().toISOString().split('T')[0]}.csv`);
  link.style.visibility = 'hidden';
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);
  URL.revokeObjectURL(url);
}

