/**
 * Statistics calculation utilities for approver performance
 */

import type { ApproverPerformanceStats, ApproverPerformanceRequest } from '../types/approverPerformance.types';

export function calculateApproverStats(
  allFilteredRequests: ApproverPerformanceRequest[]
): ApproverPerformanceStats {
  const filtered = allFilteredRequests;
  
  // Count by approver's approval status (what the approver actually did)
  const approvedByApprover = filtered.filter(r => {
    const status = (r.approvalStatus || '').toLowerCase();
    return status === 'approved';
  }).length;
  
  const rejectedByApprover = filtered.filter(r => {
    const status = (r.approvalStatus || '').toLowerCase();
    return status === 'rejected';
  }).length;
  
  const pendingByApprover = filtered.filter(r => {
    const status = (r.approvalStatus || '').toLowerCase();
    return ['pending', 'in_progress', 'in-progress'].includes(status);
  }).length;
  
  // Count closed requests - check overall request status (wf.status = 'CLOSED')
  // Closed requests are those that have been finalized with a conclusion remark
  const closedByApprover = filtered.filter(r => {
    const requestStatus = (r.status || '').toLowerCase();
    return requestStatus === 'closed';
  }).length;
  
  // TAT compliance stats - check isBreached flag OR slaStatus === 'breached'
  // This includes pending requests that have breached their TAT
  const breached = filtered.filter(r => {
    const isBreached = r.isBreached === true || r.isBreached === 1;
    const slaStatusBreached = (r.slaStatus || '').toLowerCase() === 'breached';
    return isBreached || slaStatusBreached;
  }).length;
  
  // Compliant: completed actions (approved/rejected) that are NOT breached
  // OR pending requests that haven't breached yet
  const compliant = filtered.filter(r => {
    const status = (r.approvalStatus || '').toLowerCase();
    const isCompleted = status === 'approved' || status === 'rejected';
    const isPending = ['pending', 'in_progress', 'in-progress'].includes(status);
    const isNotBreached = !(r.isBreached === true || r.isBreached === 1) && 
                         (r.slaStatus || '').toLowerCase() !== 'breached';
    
    // Completed and not breached = compliant
    // Pending and not breached = also counts as compliant (hasn't breached yet)
    return (isCompleted && isNotBreached) || (isPending && isNotBreached);
  }).length;
  
  // Calculate approval rate (based on completed actions)
  const completedActions = approvedByApprover + rejectedByApprover;
  const approvalRate = completedActions > 0 
    ? Math.round((approvedByApprover / completedActions) * 100) 
    : 0;
  
  // Calculate rejection rate
  const rejectionRate = completedActions > 0 
    ? Math.round((rejectedByApprover / completedActions) * 100) 
    : 0;
  
  // Calculate TAT compliance rate
  // Use total requests (not just completed) to include pending requests in compliance calculation
  // Use Math.floor to ensure consistent rounding with dashboard (prevents 79.5% vs 80% discrepancy)
  const totalForCompliance = filtered.length;
  const tatComplianceRate = totalForCompliance > 0 
    ? Math.floor((compliant / totalForCompliance) * 100) 
    : 0;
  
  return {
    total: filtered.length,
    // Approver's actions
    approvedByApprover,
    rejectedByApprover,
    pendingByApprover,
    closedByApprover,
    // TAT stats
    breached,
    compliant,
    // Rates
    approvalRate,
    rejectionRate,
    tatComplianceRate,
    completedActions
  };
}

