-- C.2: per-recipient webhook event dedup.
--
-- The legacy `idx_de_dedup` index keyed off (document_id, signature_hash)
-- where signature_hash was a body-content hash. A RECIPIENT_SIGNED webhook
-- for signer A and a separate RECIPIENT_SIGNED for signer B on the same
-- envelope would have identical bodies in some Documenso versions, causing
-- the second to be incorrectly deduplicated as a re-delivery.
--
-- This migration adds:
--   1. A nullable `recipient_email` column to document_events.
--   2. A partial unique index on (document_id, recipient_email, event_type)
--      where recipient_email IS NOT NULL - so per-recipient events dedup
--      independently while legacy events without recipient context fall
--      through to the existing signature_hash dedup.

ALTER TABLE document_events
  ADD COLUMN IF NOT EXISTS recipient_email text;

CREATE UNIQUE INDEX IF NOT EXISTS idx_de_per_recipient_dedup
  ON document_events (document_id, recipient_email, event_type)
  WHERE recipient_email IS NOT NULL;
