-- ============================================================================
-- EduAdvise CRM — Phase 5 RLS
-- Accountant masters: read all, write master.update.
-- fee_payments + university_commissions: branch-scoped, write finance.update.
-- ============================================================================

do $$
declare t text;
begin
  foreach t in array array[
    'account_statuses','expense_types','banking_details','currency_rates',
    'plans_main','plans_sub'
  ]
  loop
    execute format('alter table public.%I enable row level security', t);
    execute format($p$create policy "read %1$s" on public.%1$I for select to authenticated using (true)$p$, t);
    execute format($p$create policy "manage %1$s" on public.%1$I for all to authenticated
      using (public.has_permission('master','update'))
      with check (public.has_permission('master','update'))$p$, t);
  end loop;
end $$;

alter table public.fee_payments enable row level security;
create policy "read fee_payments" on public.fee_payments
  for select to authenticated using (
    public.is_super_admin()
    or branch_id in (select public.current_user_branch_ids())
    or public.has_permission('finance','read')
  );
create policy "manage fee_payments" on public.fee_payments
  for all to authenticated
  using (public.has_permission('finance','update'))
  with check (public.has_permission('finance','update'));

alter table public.university_commissions enable row level security;
create policy "read university_commissions" on public.university_commissions
  for select to authenticated using (
    public.is_super_admin()
    or branch_id in (select public.current_user_branch_ids())
    or public.has_permission('finance','read')
    or public.has_permission('reports','read')
  );
create policy "manage university_commissions" on public.university_commissions
  for all to authenticated
  using (public.has_permission('finance','update'))
  with check (public.has_permission('finance','update'));
