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

export const CollectionSyncManager = {
  async syncCollectionToOwner(collectionId) {
    try {
      const { data: collection, error: cError } = await supabase
        .from('collections')
        .select('*')
        .eq('id', collectionId)
        .single();
      
      if (cError) throw cError;
      if (!collection.owner_id) throw new Error("No owner linked to this collection.");

      const { error: uError } = await supabase
        .from('owners')
        .update({
          balance: collection.amount_owed,
        })
        .eq('id', collection.owner_id);

      if (uError) throw uError;

      await this.logSyncOperation('collection_to_owner', collection.association_id, collection.id, 'success');
      return { success: true };

    } catch (error) {
      console.error("Sync error:", error);
      await this.logSyncOperation('collection_to_owner', null, collectionId, 'failed', error.message);
      return { success: false, error: error.message };
    }
  },

  async syncOwnerToCollection(ownerId) {
    try {
      const { data: owner, error: oError } = await supabase
        .from('owners')
        .select('*')
        .eq('id', ownerId)
        .single();
        
      if (oError) throw oError;

      const { error: uError } = await supabase
        .from('collections')
        .update({
          amount_owed: owner.balance || 0,
        })
        .eq('owner_id', ownerId);

      if (uError) throw uError;

      await this.logSyncOperation('owner_to_collection', owner.association_id, ownerId, 'success');
      return { success: true };

    } catch (error) {
      console.error("Sync error:", error);
      return { success: false, error: error.message };
    }
  },

  async reconcileData(associationId) {
    const report = {
      mismatches: [],
      fixed: 0,
      errors: 0
    };

    try {
      const { data: collections } = await supabase.from('collections').select('*').eq('association_id', associationId);
      const { data: owners } = await supabase.from('owners').select('*').eq('association_id', associationId).eq('status', 'active');

      if (!collections || !owners) return report;

      for (const collection of collections) {
        if (!collection.owner_id) continue;
        
        const owner = owners.find(o => o.id === collection.owner_id);
        if (!owner) continue;

        const mismatch = Number(owner.balance) !== Number(collection.amount_owed);

        if (mismatch) {
          report.mismatches.push({
            collectionId: collection.id,
            ownerId: owner.id,
            diff: {
              balance: { owner: owner.balance, collection: collection.amount_owed }
            }
          });

          const { error } = await supabase
            .from('owners')
            .update({
              balance: collection.amount_owed,
            })
            .eq('id', owner.id);
          
          if (!error) report.fixed++;
          else report.errors++;
        }
      }
      return report;
    } catch (err) {
      console.error("Reconciliation failed", err);
      throw err;
    }
  },

  async logSyncOperation(type, associationId, recordId, status, errorMessage = null) {
    if (status === 'failed') {
      console.error(`[SyncLog] ${type} failed for record ${recordId}:`, errorMessage);
    }
  }
};
