/**
 * Transformers for converting API request data to display format
 */

import type { ConvertedRequest } from '../types/requests.types';

export function transformRequest(req: any): ConvertedRequest {
  const createdAt = req.submittedAt || req.submitted_at || req.createdAt || req.created_at;
  const priority = (req.priority || '').toString().toLowerCase();
  const status = (req.status || '').toString().toUpperCase();
  
  // Extract current approver - handle multiple field name variations
  let currentApprover = '—';
  let approverLevel = '—';
  
  // Try to get current approver from various possible locations
  const currentApproverObj = req.currentApprover || req.current_approver || req.currentApproverData;
  if (currentApproverObj) {
    // Handle object format: { name, email, approverName, approverEmail, etc. }
    currentApprover = currentApproverObj.name || 
                     currentApproverObj.approverName || 
                     currentApproverObj.displayName ||
                     currentApproverObj.email || 
                     currentApproverObj.approverEmail || 
                     '—';
  } else if (req.approvals && Array.isArray(req.approvals) && req.approvals.length > 0) {
    // For completed requests, show the last approver (final approver)
    // For active requests, find the current pending/in-progress approver
    const activeApproval = req.approvals.find((a: any) => {
      const aStatus = (a.status || '').toString().toUpperCase();
      return aStatus === 'PENDING' || aStatus === 'IN_PROGRESS';
    });
    
    if (activeApproval) {
      // Active request - show current approver
      currentApprover = activeApproval.approverName || 
                       activeApproval.approver?.name ||
                       activeApproval.approver?.displayName ||
                       activeApproval.approverEmail || 
                       activeApproval.approver?.email || 
                       '—';
    } else {
      // Completed request - show final approver (last one in the array, or highest level)
      const sortedApprovals = [...req.approvals].sort((a: any, b: any) => {
        const aLevel = a.levelNumber || a.level_number || 0;
        const bLevel = b.levelNumber || b.level_number || 0;
        return bLevel - aLevel; // Sort descending to get highest level
      });
      const finalApproval = sortedApprovals[0];
      if (finalApproval) {
        currentApprover = finalApproval.approverName || 
                         finalApproval.approver?.name ||
                         finalApproval.approver?.displayName ||
                         finalApproval.approverEmail || 
                         finalApproval.approver?.email || 
                         '—';
      }
    }
  }
  
  // Extract approval level information - handle multiple field name variations
  const currentLevel = req.currentLevel || req.current_level || req.currentLevelNumber || req.current_level_number;
  const totalLevels = req.totalLevels || req.total_levels || req.totalLevelsCount || req.total_levels_count;
  
  if (currentLevel && totalLevels) {
    approverLevel = `${currentLevel} of ${totalLevels}`;
  } else if (req.approvals && Array.isArray(req.approvals) && req.approvals.length > 0) {
    // Fallback: calculate from approvals array
    const activeApproval = req.approvals.find((a: any) => {
      const aStatus = (a.status || '').toString().toUpperCase();
      return aStatus === 'PENDING' || aStatus === 'IN_PROGRESS';
    });
    
    if (activeApproval) {
      const levelNum = activeApproval.levelNumber || activeApproval.level_number || 0;
      const total = totalLevels || req.approvals.length;
      approverLevel = `${levelNum} of ${total}`;
    } else if (totalLevels) {
      // Completed request - show final level
      approverLevel = `${totalLevels} of ${totalLevels}`;
    }
  } else if (req.currentStep && req.totalSteps) {
    // Alternative field names
    approverLevel = `${req.currentStep} of ${req.totalSteps}`;
  }
  
  return {
    id: req.requestNumber || req.request_number || req.requestId || req.id || req.request_id,
    requestId: req.requestId || req.id || req.request_id,
    displayId: req.requestNumber || req.request_number || req.id,
    title: req.title,
    description: req.description,
    status: status.toLowerCase().replace('_','-'),
    priority: priority,
    department: req.department || req.initiator?.department,
    submittedDate: req.submittedAt || (req.createdAt ? new Date(req.createdAt).toISOString().split('T')[0] : undefined),
    createdAt: createdAt,
    currentApprover: currentApprover,
    approverLevel: approverLevel,
    templateType: req.templateType || req.template_type,
    workflowType: req.workflowType || req.workflow_type,
    templateName: req.templateName || req.template_name,
    form16Submission: req.form16Submission ?? null,
  };
}

export function transformRequests(requests: any[]): ConvertedRequest[] {
  return Array.isArray(requests) ? requests.map(transformRequest) : [];
}

