import { supabase } from '@/integrations/supabase/client';
import { format, differenceInDays } from 'date-fns';

/**
 * Fetches and categorizes collection data for the Month-End Report.
 * Categorizes into 'open' and 'resolved'.
 * Includes detailed financial breakdown to match standalone Collections Report.
 * 
 * @param {Date} startDate 
 * @param {Date} endDate 
 * @param {string} associationId 
 */
export async function fetchStandardizedCollectionsReport(startDate, endDate, associationId) {
  const { data: collections, error } = await supabase
    .from('collections')
    .select(`
      *,
      owners(id, first_name, last_name)
    `)
    .eq('association_id', associationId)
    .order('created_at', { ascending: false });

  if (error) {
    console.error('Error fetching collections for report:', error);
    return { open: [], resolved: [], stats: { total: 0, openCount: 0, resolvedCount: 0, resolutionRate: 0 } };
  }

  const openItems = [];
  const resolvedItems = [];
  
  const toCurrency = (val) => `$${Number(val || 0).toFixed(2)}`;

  collections.forEach(c => {
    const isResolved = c.status === 'resolved' || c.status === 'closed';
    
    const itemDate = new Date(c.updated_at);
    const inDateRange = itemDate >= startDate && itemDate <= endDate;
    
    if (isResolved && !inDateRange) {
      return; 
    }

    const totalDue = Number(c.amount_owed || 0);

    const item = {
      id: c.id,
      owner: c.owners ? `${c.owners.first_name} ${c.owners.last_name}` : 'Unknown',
      status: c.status || 'open',
      totalDue: toCurrency(totalDue),
      dateOpened: c.created_at ? format(new Date(c.created_at), 'MM/dd/yyyy') : '-',
      dateResolved: isResolved ? format(new Date(c.updated_at), 'MM/dd/yyyy') : '-',
      daysOpen: c.created_at ? differenceInDays(new Date(), new Date(c.created_at)) : 0,
      raw: c
    };

    if (isResolved) {
      resolvedItems.push(item);
    } else {
      openItems.push(item);
    }
  });

  const total = openItems.length + resolvedItems.length;
  const rate = total > 0 ? Math.round((resolvedItems.length / total) * 100) : 0;

  return {
    open: openItems,
    resolved: resolvedItems,
    stats: {
      total,
      openCount: openItems.length,
      resolvedCount: resolvedItems.length,
      resolutionRate: rate
    }
  };
}
