-- Make GL auto-posting an explicit per-company flag instead of inferring it from
-- the presence of non-acmacc journal entries. The old heuristic
-- (accounting.gl_managed = "no foreign/imported journal entries") broke the moment
-- a normal MANUAL journal entry (external_source null) was added to a managed
-- company — it silently flipped the company to "unmanaged" and disabled all GL
-- automation. Companies with a large imported GL are flagged off; platform-managed
-- companies default on.
alter table accounting.companies add column if not exists gl_auto_post boolean not null default true;

update accounting.companies c set gl_auto_post = false
where (
  select count(*) from accounting.journal_entries je
  where je.company_id = c.id
    and (je.external_source is null or je.external_source not like 'acmacc_%')
) > 5;

create or replace function accounting.gl_managed(_company_id uuid)
returns boolean language sql stable security definer set search_path to 'public','accounting' as $$
  select coalesce((select gl_auto_post from accounting.companies where id = _company_id), true);
$$;
