import Papa from 'papaparse';

export const REQUIRED_COLUMNS = ['unit_id', 'account_number', 'amount', 'fee_type'];

export const VALID_FEE_TYPES = [
  'Assessments',
  'Late Fees',
  'Interest',
  'Legal Fees',
  'Admin Fees'
];

export const validateCSVHeaders = (headers) => {
  const missing = REQUIRED_COLUMNS.filter(col => !headers.includes(col));
  if (missing.length > 0) {
    return { valid: false, error: `Missing required columns: ${missing.join(', ')}` };
  }
  return { valid: true };
};

export const validateRow = (row, rowIndex) => {
  const errors = [];
  
  // Validate Amount
  const amount = parseFloat(row.amount);
  if (isNaN(amount) || amount < 0) {
    errors.push(`Row ${rowIndex + 1}: Amount must be a positive number.`);
  }

  // Validate Fee Type
  if (!VALID_FEE_TYPES.includes(row.fee_type)) {
    errors.push(`Row ${rowIndex + 1}: Invalid fee_type '${row.fee_type}'. Must be one of: ${VALID_FEE_TYPES.join(', ')}.`);
  }

  // Basic required checks
  if (!row.unit_id) errors.push(`Row ${rowIndex + 1}: Missing unit_id.`);
  if (!row.account_number) errors.push(`Row ${rowIndex + 1}: Missing account_number.`);

  return errors;
};

export const parseCSVFile = (file) => {
  return new Promise((resolve, reject) => {
    Papa.parse(file, {
      header: true,
      skipEmptyLines: true,
      transformHeader: (header) => header.trim().toLowerCase().replace(/\s+/g, '_'),
      complete: (results) => {
        resolve(results.data);
      },
      error: (error) => {
        reject(error);
      }
    });
  });
};

export const consolidateRows = (rows) => {
  // Groups by account_number (assuming unique identifier for the delinquency record target)
  // In reality, we might group by unit_id AND account_number, but typically account_number is unique enough per client.
  // We'll use a composite key for grouping to be safe.
  
  const groups = {};

  rows.forEach(row => {
    const key = `${row.unit_id}_${row.account_number}`;
    if (!groups[key]) {
      groups[key] = {
        unit_id: row.unit_id,
        account_number: row.account_number,
        assessments: 0,
        late_fees: 0,
        interest: 0,
        legal_fees: 0,
        admin_fees: 0
      };
    }

    const amount = parseFloat(row.amount) || 0;
    switch(row.fee_type) {
      case 'Assessments': groups[key].assessments += amount; break;
      case 'Late Fees': groups[key].late_fees += amount; break;
      case 'Interest': groups[key].interest += amount; break;
      case 'Legal Fees': groups[key].legal_fees += amount; break;
      case 'Admin Fees': groups[key].admin_fees += amount; break;
    }
  });

  return Object.values(groups);
};