-- 0064_payments_permission.sql
-- ----------------------------------------------------------------------------
-- Carve out a dedicated `payments` resource from `invoices.record_payment`.
-- Existing role rows + per-user permission overrides are backfilled so the
-- new resource defaults to whatever record_payment was, preventing silent
-- access loss when the call sites switch over.

UPDATE roles
SET permissions = permissions || jsonb_build_object(
  'payments', jsonb_build_object(
    'view',   COALESCE((permissions->'invoices'->>'view')::boolean,            false),
    'record', COALESCE((permissions->'invoices'->>'record_payment')::boolean,  false),
    'delete', COALESCE((permissions->'invoices'->>'record_payment')::boolean,  false)
  )
)
WHERE permissions IS NOT NULL
  AND NOT (permissions ? 'payments');

-- Per-user overrides store a Partial<RolePermissions> as JSONB. Mirror an
-- explicit invoices.record_payment leaf into payments.{record, delete} so
-- "Alice can record payments even though her role can't" survives the
-- carve-out.
UPDATE user_permission_overrides
SET permission_overrides = permission_overrides || jsonb_build_object(
  'payments', jsonb_build_object(
    'record', (permission_overrides->'invoices'->>'record_payment')::boolean,
    'delete', (permission_overrides->'invoices'->>'record_payment')::boolean
  )
)
WHERE permission_overrides ? 'invoices'
  AND (permission_overrides->'invoices') ? 'record_payment'
  AND NOT (permission_overrides ? 'payments');
