-- Expand/contract safety: remove duplicate logical outbox rows before enforcing idempotency.
DELETE FROM outbox o
USING outbox older
WHERE o.aggregate_type = older.aggregate_type
  AND o.aggregate_id = older.aggregate_id
  AND o.event_type = older.event_type
  AND o.id <> older.id
  AND (o.created_at, o.id) > (older.created_at, older.id);

CREATE UNIQUE INDEX IF NOT EXISTS outbox_aggregate_event_uniq
  ON outbox (aggregate_type, aggregate_id, event_type);
