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

/**
 * Service to suggest Chart of Accounts mapping based on AI parsed data.
 */
export async function getSuggestedAccounts({ clientId, category, transactionType = 'vendor_bill', fundType = 'operating' }) {
  let normalizedCategory = category ? category.toLowerCase().trim() : '';

  try {
    if (normalizedCategory) {
      let synQuery = supabase
        .from('category_synonym_mappings')
        .select('normalized_category')
        .eq('raw_category', normalizedCategory);
        
      if (clientId) {
         synQuery = synQuery.or(`client_id.eq.${clientId},client_id.is.null`);
      } else {
         synQuery = synQuery.is('client_id', null);
      }

      const { data: synData, error: synError } = await synQuery.limit(1).maybeSingle();
      if (!synError && synData) {
        normalizedCategory = synData.normalized_category;
      }
    }

    let query = supabase.from('coa_mapping_rules')
      .select(`
        id, category_key, fund_type, priority,
        debit_account:chart_of_accounts!debit_account_id(id, account_number, account_name, account_type),
        credit_account:chart_of_accounts!credit_account_id(id, account_number, account_name, account_type)
      `)
      .eq('transaction_type', transactionType)
      .eq('is_active', true)
      .order('priority', { ascending: false });

    if (clientId) {
      query = query.or(`client_id.eq.${clientId},client_id.is.null`);
    } else {
      query = query.is('client_id', null);
    }

    const { data: rules, error: ruleError } = await query;
    if (ruleError) throw ruleError;

    let match = null;
    let isFallback = false;

    if (rules && rules.length > 0) {
      match = rules.find(r => r.category_key === normalizedCategory && r.fund_type === fundType);
      if (!match) {
        match = rules.find(r => r.category_key === normalizedCategory && !r.fund_type);
      }
      if (!match) {
        match = rules.find(r => !r.category_key || r.category_key === '*default*');
        isFallback = true;
      }
    }

    return {
      debitAccount: match?.debit_account || null,
      creditAccount: match?.credit_account || null,
      ruleId: match?.id || null,
      isFallback,
      normalizedCategory
    };

  } catch (err) {
    console.error("COA Mapping Error:", err);
    return { debitAccount: null, creditAccount: null, isFallback: true, error: err.message };
  }
}
