// server/api/members/overdue-count.get.ts

// Helper function to calculate overdue duration
function calculateOverdueDuration(dueDate: Date, today: Date): { 
  years: number; 
  months: number; 
  totalMonths: number;
  formattedDuration: string;
} {
  const diffTime = today.getTime() - dueDate.getTime();
  const diffMonths = Math.floor(diffTime / (1000 * 60 * 60 * 24 * 30.44)); // Average days per month
  const years = Math.floor(diffMonths / 12);
  const months = diffMonths % 12;
  
  let formattedDuration = '';
  if (years > 0) {
    formattedDuration += `${years} year${years !== 1 ? 's' : ''}`;
    if (months > 0) {
      formattedDuration += ` ${months} month${months !== 1 ? 's' : ''}`;
    }
  } else {
    formattedDuration = `${diffMonths} month${diffMonths !== 1 ? 's' : ''}`;
  }
  
  return {
    years,
    months,
    totalMonths: diffMonths,
    formattedDuration: `${formattedDuration} overdue`
  };
}

export default defineEventHandler(async (event) => {
  try {
    const { getMembers } = await import('~/server/utils/nocodb');

    // Get all members
    const allMembers = await getMembers();
    
    if (!allMembers?.list) {
      return {
        success: true,
        data: { 
          count: 0,
          overdueMembers: []
        }
      };
    }

    const today = new Date();
    const overdueMembers: any[] = [];

    for (const member of allMembers.list) {
      // Check for severely overdue members (more than 1 year past due date)
      let overdueDuration = null;
      
      if (member.current_year_dues_paid === 'true' && member.membership_date_paid) {
        // If dues are marked as paid, check if it's been more than 1 year since payment
        const lastPaidDate = new Date(member.membership_date_paid);
        const oneYearFromPayment = new Date(lastPaidDate);
        oneYearFromPayment.setFullYear(oneYearFromPayment.getFullYear() + 1);
        
        if (today > oneYearFromPayment) {
          overdueDuration = calculateOverdueDuration(oneYearFromPayment, today);
        }
      } else if (member.current_year_dues_paid !== 'true') {
        // If dues are not paid, check payment due date or member since date
        let dueDate: Date;
        
        if (member.payment_due_date) {
          dueDate = new Date(member.payment_due_date);
        } else if (member.member_since) {
          // Fallback: 1 year from member since date
          dueDate = new Date(member.member_since);
          dueDate.setFullYear(dueDate.getFullYear() + 1);
        } else {
          // Skip if we can't determine due date
          continue;
        }
        
        // Check if more than 1 year overdue
        const oneYearOverdue = new Date(dueDate);
        oneYearOverdue.setFullYear(oneYearOverdue.getFullYear() + 1);
        
        if (today > oneYearOverdue) {
          overdueDuration = calculateOverdueDuration(oneYearOverdue, today);
        }
      }

      if (overdueDuration) {
        overdueMembers.push({
          id: member.Id,
          name: member.FullName || `${member.first_name} ${member.last_name}`,
          email: member.email,
          status: member.membership_status,
          overdueDuration: overdueDuration.formattedDuration,
          totalMonthsOverdue: overdueDuration.totalMonths,
          isInactive: member.membership_status === 'Inactive'
        });
      }
    }

    // Sort by most overdue first
    overdueMembers.sort((a, b) => b.totalMonthsOverdue - a.totalMonthsOverdue);

    return {
      success: true,
      data: { 
        count: overdueMembers.length,
        overdueMembers: overdueMembers
      }
    };

  } catch (error: any) {
    console.error('[API] Error fetching overdue count:', error);
    
    throw createError({
      statusCode: error.statusCode || 500,
      statusMessage: error.message || 'Failed to fetch overdue count'
    });
  }
});
