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

/**
 * Fetches the central Chart of Accounts list globally.
 */
export async function fetchChartOfAccountsForClient(clientId, fields = '*') {
  const { data, error } = await supabase
    .from('chart_of_accounts')
    .select(fields)
    .order('account_number', { ascending: true });
    
  if (error) {
    console.error('Error fetching global chart of accounts:', error);
    throw error;
  }
  
  return data || [];
}

/**
 * Fetches combined accounts globally (Chart of Accounts, marking Bank Accounts as assets).
 */
export async function fetchCombinedAccounts(clientId) {
  try {
    const { data, error } = await supabase
      .from('chart_of_accounts')
      .select('*')
      .eq('is_active', true)
      .order('account_number', { ascending: true });
      
    if (error) throw error;

    return (data || []).map(c => ({
      ...c,
      is_bank: c.detail_type === 'bank_account' || (c.account_name && c.account_name.toLowerCase().includes('bank'))
    })).sort((a, b) => {
       if (a.is_bank && !b.is_bank) return -1;
       if (!a.is_bank && b.is_bank) return 1;
       return (a.account_number || '').localeCompare(b.account_number || '');
    });
  } catch (err) {
    console.error('Error fetching combined accounts:', err);
    return [];
  }
}

/**
 * Seeds a standard multi-level Chart of Accounts globally.
 */
export async function seedStandardChartOfAccounts() {
  const standardCOA = [
    // ASSETS (1000s)
    { ref: 'ast', number: '1000', name: 'Assets', type: 'Asset', category: 'Current assets', is_parent: true, parent: null },
    { ref: 'ca', number: '1100', name: 'Current Assets', type: 'Asset', category: 'Current assets', is_parent: true, parent: 'ast' },
    { ref: 'csh', number: '1110', name: 'Cash and Cash Equivalents', type: 'Asset', category: 'Current assets', is_parent: false, parent: 'ca' },
    { ref: 'ar', number: '1120', name: 'Accounts Receivable', type: 'Asset', category: 'Current assets', is_parent: false, parent: 'ca' },
    { ref: 'uf', number: '1130', name: 'Undeposited Funds', type: 'Asset', category: 'Current assets', is_parent: false, parent: 'ca' },
    { ref: 'nca', number: '1500', name: 'Non-Current Assets', type: 'Asset', category: 'Fixed assets', is_parent: true, parent: 'ast' },
    { ref: 'fa', number: '1510', name: 'Fixed Assets', type: 'Asset', category: 'Fixed assets', is_parent: false, parent: 'nca' },
    
    // LIABILITIES (2000s)
    { ref: 'lib', number: '2000', name: 'Liabilities', type: 'Liability', category: 'Current liabilities', is_parent: true, parent: null },
    { ref: 'cl', number: '2100', name: 'Current Liabilities', type: 'Liability', category: 'Current liabilities', is_parent: true, parent: 'lib' },
    { ref: 'ap', number: '2110', name: 'Accounts Payable', type: 'Liability', category: 'Current liabilities', is_parent: false, parent: 'cl' },
    { ref: 'ltl', number: '2500', name: 'Long-Term Liabilities', type: 'Liability', category: 'Fixed liabilities', is_parent: true, parent: 'lib' },
    { ref: 'ln', number: '2510', name: 'Loans Payable', type: 'Liability', category: 'Fixed liabilities', is_parent: false, parent: 'ltl' },

    // EQUITY (3000s)
    { ref: 'eqt', number: '3000', name: 'Equity', type: 'Equity', category: 'Equity', is_parent: true, parent: null },
    { ref: 're', number: '3199', name: 'Retained Earnings', type: 'Equity', category: 'Equity', is_parent: false, parent: 'eqt' },
    { ref: 'fb', number: '3200', name: 'Fund Balance', type: 'Equity', category: 'Equity', is_parent: false, parent: 'eqt' },
    { ref: 'div', number: '3300', name: 'Dividends', type: 'Equity', category: 'Equity', is_parent: false, parent: 'eqt' },

    // REVENUE (4000s)
    { ref: 'rev', number: '4000', name: 'Revenue', type: 'Equity', category: 'Income', is_parent: true, parent: null },
    { ref: 'oprev', number: '4100', name: 'Operating Revenue', type: 'Equity', category: 'Income', is_parent: true, parent: 'rev' },
    { ref: 'asr', number: '4110', name: 'Assessment Revenue', type: 'Equity', category: 'Income', is_parent: false, parent: 'oprev' },
    { ref: 'lfr', number: '4120', name: 'Late Fee Revenue', type: 'Equity', category: 'Income', is_parent: false, parent: 'oprev' },

    // COGS (6000s)
    { ref: 'cogs', number: '6000', name: 'Cost of Goods Sold', type: 'Equity', category: 'Expenses', is_parent: true, parent: null },

    // EXPENSES (5000s)
    { ref: 'exp', number: '5000', name: 'Expenses', type: 'Equity', category: 'Expenses', is_parent: true, parent: null },
    { ref: 'opexp', number: '5100', name: 'Operating Expenses', type: 'Equity', category: 'Expenses', is_parent: true, parent: 'exp' },
    { ref: 'mnt', number: '5110', name: 'Maintenance & Repairs', type: 'Equity', category: 'Expenses', is_parent: false, parent: 'opexp' },
    { ref: 'utl', number: '5120', name: 'Utilities', type: 'Equity', category: 'Expenses', is_parent: false, parent: 'opexp' },
    { ref: 'ins', number: '5130', name: 'Insurance', type: 'Equity', category: 'Expenses', is_parent: false, parent: 'opexp' },
    { ref: 'adm', number: '5140', name: 'Administrative', type: 'Equity', category: 'Expenses', is_parent: false, parent: 'opexp' },
    { ref: 'nopexp', number: '5500', name: 'Non-Operating Expenses', type: 'Equity', category: 'Non-operating expenses', is_parent: true, parent: 'exp' },
    { ref: 'int', number: '5510', name: 'Interest Expense', type: 'Equity', category: 'Non-operating expenses', is_parent: false, parent: 'nopexp' },

    // OCI (7000s)
    { ref: 'oci', number: '7000', name: 'Other Comprehensive Income', type: 'Equity', category: 'Income', is_parent: true, parent: null }
  ];

  const idMap = {};
  
  const insertPass = async (nodes) => {
    for (const node of nodes) {
      if (!node.name || !node.type) continue;

      const { data: existing } = await supabase
        .from('chart_of_accounts')
        .select('id')
        .eq('account_number', node.number)
        .limit(1)
        .maybeSingle();

      if (existing) {
        idMap[node.ref] = existing.id;
        continue;
      }

      const payload = {
        account_number: node.number,
        account_name: node.name,
        account_type: node.type,
        parent_account_id: node.parent ? idMap[node.parent] : null,
        is_active: true
      };
      
      try {
        const { data, error } = await supabase.from('chart_of_accounts').insert(payload).select('id').single();
        if (error) throw error;
        if (data) idMap[node.ref] = data.id;
      } catch (err) {
        console.error(`Error inserting standard COA node ${node.name}:`, err.message);
      }
    }
  };

  const roots = standardCOA.filter(n => !n.parent);
  const tier1 = standardCOA.filter(n => n.parent && roots.some(r => r.ref === n.parent));
  const tier2 = standardCOA.filter(n => n.parent && tier1.some(t => t.ref === n.parent));

  await insertPass(roots);
  await insertPass(tier1);
  await insertPass(tier2);

  return true;
}
