import { supabase } from '@/integrations/supabase/client';

/**
 * Verifies consistency between collections, property owners, and financial records.
 */
export async function verifyCollectionSync(clientId) {
  if (!clientId) return { consistent: true, mismatches: [], stats: {} };

  const report = {
    consistent: true,
    mismatches: [],
    stats: { collections: 0, owners: 0 }
  };

  try {
    const { data: collections, error: cError } = await supabase
      .from('collections')
      .select('id, property_id, address, status, stage, amount_due')
      .eq('client_id', clientId);
    
    const { data: owners, error: oError } = await supabase
      .from('property_owners')
      .select('id, property_address, collection_status, collection_stage, balance')
      .eq('client_id', clientId);

    if (cError || oError) throw (cError || oError);

    report.stats.collections = collections.length;
    report.stats.owners = owners.length;

    for (const collection of collections) {
      if (!collection.property_id) continue;

      const owner = owners.find(o => o.id === collection.property_id);
      
      if (!owner) {
        report.mismatches.push({
          type: 'MISSING_OWNER',
          collectionId: collection.id,
          message: `Collection ${collection.id} references non-existent property_id ${collection.property_id}`
        });
        report.consistent = false;
        continue;
      }

      if (collection.status !== owner.collection_status) {
        report.mismatches.push({
          type: 'STATUS_MISMATCH',
          collectionId: collection.id,
          ownerId: owner.id,
          expected: collection.status,
          actual: owner.collection_status
        });
        report.consistent = false;
      }

      if (collection.stage !== owner.collection_stage) {
        report.mismatches.push({
          type: 'STAGE_MISMATCH',
          collectionId: collection.id,
          ownerId: owner.id,
          expected: collection.stage,
          actual: owner.collection_stage
        });
        report.consistent = false;
      }

      const collBal = Number(collection.amount_due || 0);
      const ownerBal = Number(owner.balance || 0);
      if (Math.abs(collBal - ownerBal) > 0.01) {
        report.mismatches.push({
          type: 'BALANCE_MISMATCH',
          collectionId: collection.id,
          ownerId: owner.id,
          expected: collBal,
          actual: ownerBal
        });
        report.consistent = false;
      }
    }

    return report;

  } catch (error) {
    console.error("Verification failed:", error);
    return { consistent: false, mismatches: [{ type: 'ERROR', message: error.message }], stats: {} };
  }
}
