-- Prevent an approver from approving, rejecting, reversing, or marking paid
-- an invoice that belongs to their OWN agent_id — self-approval defeats the
-- purpose of the approval step. Real database-level restriction, not a UI
-- convenience: Edwin (and potentially others) can hold both
-- is_invoice_approver=true and a real agent_id at the same time, so a
-- client-side hide alone would not actually stop a direct API/console call
-- from approving/paying their own invoice.
--
-- `agent_id IS DISTINCT FROM current_agent_id()` (not `!=`) is deliberate:
-- for an approver with no agent_id of their own (agent_id null — the common
-- case, e.g. a pure reviewer/approver account), `agent_id != NULL` would
-- evaluate to NULL/false for every row under plain equality semantics and
-- block them from approving anything at all. IS DISTINCT FROM treats NULL
-- as a real, comparable value, so it correctly allows them to act on any
-- invoice when they have no agent_id of their own to conflict with, and
-- only blocks the case where agent_id actually matches their own.
--
-- Scope: this only touches invoices_update_approver. invoices_update_owner
-- already can't reach 'approved'/'paid' at all (its allowed status set is
-- draft/submitted/rejected only), so self-approval was only ever reachable
-- through the approver policy — this is the single place that needed it.

drop policy if exists "invoices_update_approver" on public.invoices;

create policy "invoices_update_approver"
on public.invoices
for update
to authenticated
using (
  public.is_invoice_approver()
  and agent_id is distinct from public.current_agent_id()
)
with check (
  public.is_invoice_approver()
  and agent_id is distinct from public.current_agent_id()
);
