/**
 * CSV export utilities for requests
 */

import { format } from 'date-fns';
import dayjs from 'dayjs';
import isSameOrAfter from 'dayjs/plugin/isSameOrBefore';
import isSameOrBefore from 'dayjs/plugin/isSameOrAfter';
import type { RequestFilters } from '../types/requests.types';
import { applyFilters } from './requestFilters';

dayjs.extend(isSameOrAfter);
dayjs.extend(isSameOrBefore);

export function formatDateForCSV(date: Date | string | undefined): string {
  if (!date) return 'N/A';
  try {
    const dateObj = typeof date === 'string' ? new Date(date) : date;
    return format(dateObj, 'yyyy-MM-dd HH:mm:ss');
  } catch {
    return 'N/A';
  }
}

export async function exportRequestsToCSV(
  allData: any[],
  filters: RequestFilters
): Promise<void> {
  // Apply the same filtering logic
  const filteredData = applyFilters(allData, filters);

  // Convert to CSV format
  const csvRows = [
    ['Request Number', 'Title', 'Status', 'Priority', 'Initiator', 'Department', 'Current Approver', 'Approval Level', 'Submitted Date', 'Description'].join(',')
  ];

  filteredData.forEach((req: any) => {
    const status = (req.status || '').toString().toLowerCase().replace('_', '-');
    const priority = (req.priority || '').toString().toLowerCase();
    const initiatorName = req.initiator?.displayName || req.initiator?.email || req.initiatorName || 'N/A';
    const department = req.department || req.initiator?.department || 'N/A';
    const currentApprover = req.currentApprover?.displayName || req.currentApprover?.email || req.currentApproverName || 'N/A';
    const approverLevel = req.currentApproverLevel || req.approvalLevel || req.currentLevel || 'N/A';
    const submittedDate = formatDateForCSV(req.submittedAt || req.createdAt || req.submitted_at || req.created_at);
    const description = (req.description || '').replace(/"/g, '""').replace(/\n/g, ' ').replace(/\r/g, '');

    const row = [
      req.requestNumber || req.request_number || '',
      `"${(req.title || '').replace(/"/g, '""')}"`,
      status,
      priority,
      `"${initiatorName.replace(/"/g, '""')}"`,
      `"${department.replace(/"/g, '""')}"`,
      `"${currentApprover.replace(/"/g, '""')}"`,
      approverLevel,
      submittedDate,
      `"${description}"`
    ];
    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', `requests-export-${new Date().toISOString().split('T')[0]}.csv`);
  link.style.visibility = 'hidden';
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);
  URL.revokeObjectURL(url);
}

