
/**
 * Utility functions for safely deleting records that might have foreign key references.
 */
export const safeDeleteJournalEntry = async (supabase, entryId, toast) => {
  try {
    const { data: linkedJEs, error: err1 } = await supabase
      .from('journal_entries')
      .select('id')
      .eq('linked_entry_id', entryId);
      
    if (err1) throw err1;
    
    if (linkedJEs && linkedJEs.length > 0) {
      if (toast) toast({ title: 'Cleaning up links', description: 'This entry is linked to other journal entries. Clearing links before deletion...' });
      const { error: clearErr } = await supabase
        .from('journal_entries')
        .update({ linked_entry_id: null })
        .eq('linked_entry_id', entryId);
      if (clearErr) throw clearErr;
    }

    const { data: matchedTx, error: err2 } = await supabase
      .from('bank_transactions')
      .select('id')
      .eq('matched_journal_entry_id', entryId);
      
    if (err2) throw err2;

    if (matchedTx && matchedTx.length > 0) {
       if (toast) toast({ title: 'Cleaning up links', description: 'This entry is matched to bank transactions. Un-linking...' });
      const { error: clearTxErr } = await supabase
        .from('bank_transactions')
        .update({ matched_journal_entry_id: null, is_reconciled: false, reconciled_at: null })
        .eq('matched_journal_entry_id', entryId);
      if (clearTxErr) throw clearTxErr;
    }

    const { error: delErr } = await supabase
      .from('journal_entries')
      .delete()
      .eq('id', entryId);
      
    if (delErr) throw delErr;
    return true;
  } catch (error) {
    console.error("Safe delete error (Journal Entry):", error);
    throw new Error(error.message || "An unexpected error occurred while deleting.");
  }
};

export const safeDeleteUnitTransaction = async (supabase, txId, toast) => {
    try {
        const { data: linkedTxs, error: err1 } = await supabase
            .from('unit_transactions')
            .select('id')
            .eq('related_transaction_id', txId);
        
        if (err1) throw err1;

        if (linkedTxs && linkedTxs.length > 0) {
            if (toast) toast({ title: 'Cleaning up links', description: 'Clearing links before deletion...' });
            const { error: clearErr } = await supabase
                .from('unit_transactions')
                .update({ related_transaction_id: null })
                .eq('related_transaction_id', txId);
            if (clearErr) throw clearErr;
        }

        const { data: intents, error: err2 } = await supabase
            .from('stripe_payment_intents')
            .select('id')
            .eq('unit_transaction_id', txId);
        
        if (!err2 && intents && intents.length > 0) {
             if (toast) toast({ title: 'Cleaning up links', description: 'Unlinking Stripe payment intent...' });
            await supabase.from('stripe_payment_intents').update({ unit_transaction_id: null }).eq('unit_transaction_id', txId);
        }

        const { error: delErr } = await supabase
            .from('unit_transactions')
            .delete()
            .eq('id', txId);
        
        if (delErr) throw delErr;
        return true;
    } catch (error) {
        console.error("Safe delete error (Unit Tx):", error);
        throw new Error(error.message || "An unexpected error occurred while deleting.");
    }
};

export const safeDeleteBankTransaction = async (supabase, txId, toast) => {
    try {
        const { data: linkedTxs, error: err1 } = await supabase
            .from('bank_transactions')
            .select('id')
            .eq('related_transaction_id', txId);
        
        if (err1) throw err1;

        if (linkedTxs && linkedTxs.length > 0) {
             if (toast) toast({ title: 'Cleaning up links', description: 'Clearing links before deletion...' });
            const { error: clearErr } = await supabase
                .from('bank_transactions')
                .update({ related_transaction_id: null })
                .eq('related_transaction_id', txId);
            if (clearErr) throw clearErr;
        }

        const { error: delErr } = await supabase
            .from('bank_transactions')
            .delete()
            .eq('id', txId);
            
        if (delErr) throw delErr;
        return true;
    } catch (error) {
        console.error("Safe delete error (Bank Tx):", error);
        throw new Error(error.message || "An unexpected error occurred while deleting.");
    }
};
