-- Bridgewater: record the missing opening fund balance as equity.
--
-- Bridgewater's GL was imported as ~22,300 single-sided postings (a transaction
-- register, not double-entry pairs). As a result the trial balance is internally
-- unbalanced: total debits exceed total credits by exactly 130,348.76, and equity
-- carries an abnormal debit balance. The signature is an import that brought in all
-- the ACTIVITY (assets, income, expense, etc.) but never the opening fund balance /
-- carried-forward equity from the prior system (Bridgewater has zero
-- opening_balances rows).
--
-- Per the owner's decision, attribute the gap to opening equity: post the missing
-- offsetting credit to an "Opening Fund Balance" equity account. Because the rest of
-- the imported GL is single-sided, the balancing leg is a single credit line whose
-- offsetting debits are already embedded in the imported asset/activity postings.
-- After this, total debits = total credits (R1 = 0) and the Balance Sheet balances:
--   Assets 731,193.60 = Liabilities 33,043.72 + Equity 90,210.00 + Net income 607,939.88.
--
-- Idempotent and reversible: keyed by external_source 'acmacc_bw_opening'; re-running
-- recomputes from the current imbalance. To undo, delete the JE/account with that key.

do $$
declare _c uuid; _eq uuid; _je uuid; _dt date; _imb numeric;
begin
  select id into _c from accounting.companies where name like 'Bridgewater%';
  if _c is null then raise exception 'Bridgewater company not found'; end if;

  -- Remove any prior balancing entry so we recompute from the live imbalance.
  delete from accounting.journal_entry_lines jl
    using accounting.journal_entries je
   where jl.journal_entry_id = je.id
     and je.company_id = _c and je.external_source = 'acmacc_bw_opening';
  delete from accounting.journal_entries
   where company_id = _c and external_source = 'acmacc_bw_opening';

  -- Exact imported-GL imbalance (debits - credits).
  select round(sum(jl.debit) - sum(jl.credit), 2) into _imb
  from accounting.journal_entry_lines jl
  join accounting.journal_entries je on je.id = jl.journal_entry_id
  where je.company_id = _c;

  if _imb is null or _imb = 0 then
    raise notice 'Bridgewater GL already balanced; nothing to post.';
    return;
  end if;

  -- Opening date = earliest GL date (so it reads as a brought-forward balance).
  select min(je.date) into _dt from accounting.journal_entries je where je.company_id = _c;

  -- Find or create the Opening Fund Balance equity account.
  select id into _eq from accounting.accounts
   where company_id = _c and type = 'equity'
     and (external_source = 'acmacc_bw_opening' or name = 'Opening Fund Balance')
   limit 1;
  if _eq is null then
    insert into accounting.accounts (company_id, code, name, type, description, external_source, external_id)
    values (_c, '3900', 'Opening Fund Balance', 'equity',
            'Carried-forward fund balance not included in the original GL import.',
            'acmacc_bw_opening', 'equity')
    returning id into _eq;
  end if;

  -- Post the missing opening equity. Imbalance is debits>credits, so we add a credit
  -- (a debit imbalance would add a debit instead).
  insert into accounting.journal_entries (company_id, date, description, external_source, external_id)
  values (_c, coalesce(_dt, current_date), 'Opening fund balance (carried forward, not in original import)',
          'acmacc_bw_opening', 'gap')
  returning id into _je;

  if _imb > 0 then
    insert into accounting.journal_entry_lines (journal_entry_id, account_id, debit, credit, description)
    values (_je, _eq, 0, _imb, 'Opening fund balance');
  else
    insert into accounting.journal_entry_lines (journal_entry_id, account_id, debit, credit, description)
    values (_je, _eq, -_imb, 0, 'Opening fund balance');
  end if;

  raise notice 'Bridgewater opening fund balance posted: %', _imb;
end$$;
