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

export const fetchTransactionGL = async (transactionId) => {
    const { data, error } = await supabase
        .from('app_gl_entries')
        .select('*')
        .eq('transaction_id', transactionId)
        .order('created_at');
    if (error) throw error;
    return data;
};

export const fetchUnitGL = async (unitId) => {
    const { data, error } = await supabase
        .from('app_gl_entries')
        .select('*')
        .eq('unit_id', unitId)
        .order('date')
        .order('created_at');
    if (error) throw error;
    return data;
};

export const fetchOwnerLedger = async (unitId) => {
    const { data, error } = await supabase
        .from('owner_ledger')
        .select('*')
        .eq('unit_id', unitId)
        .order('post_date')
        .order('created_at');
    if (error) throw error;
    return data;
};

export const fetchGLBalances = async () => {
    const { data, error } = await supabase.rpc('get_gl_account_balances');
    if (error) throw error;
    return data;
};

export const fetchFlaggedTransactions = async () => {
    const { data, error } = await supabase
        .from('transactions')
        .select(`
            id, type, amount, description, date, unit_id,
            property_owners ( property_address, owner_name )
        `)
        .eq('needs_manual_posting', true)
        .order('created_at', { ascending: false });
    if (error) throw error;
    return data;
};

export const resolveManualPosting = async (transactionId, entries) => {
    const { error } = await supabase.from('app_gl_entries').insert(entries);
    if (error) throw error;
    
    await supabase.from('transactions').update({ needs_manual_posting: false }).eq('id', transactionId);
    await supabase.from('gl_entry_logs').insert([{ transaction_id: transactionId, action: 'MANUAL_POSTING_RESOLVED', details: 'Posted manually' }]);
};
