-- Phase 6 - IMAP bounce-to-interest linking foundation
-- (POST-AUDIT-SPEC §14.9 / MASTER-PLAN §F).
--
-- Schema-only. Parser library + cron worker land in 6b/6c.
--
-- Adds bounce_status / bounce_reason / bounce_detected_at columns to
-- document_sends + a partial index so the UI's "show bounced rows" filter
-- is cheap.

ALTER TABLE document_sends
  ADD COLUMN IF NOT EXISTS bounce_status text,
  ADD COLUMN IF NOT EXISTS bounce_reason text,
  ADD COLUMN IF NOT EXISTS bounce_detected_at timestamptz;

DO $$
BEGIN
  IF NOT EXISTS (SELECT 1 FROM pg_constraint WHERE conname = 'chk_document_sends_bounce_status') THEN
    ALTER TABLE document_sends
      ADD CONSTRAINT chk_document_sends_bounce_status
      CHECK (bounce_status IS NULL OR bounce_status IN ('hard', 'soft', 'ooo'));
  END IF;
END $$;

CREATE INDEX IF NOT EXISTS idx_document_sends_bounce
  ON document_sends (port_id, bounce_detected_at)
  WHERE bounce_status IS NOT NULL;

COMMENT ON COLUMN document_sends.bounce_status IS
  'Phase 6: hard|soft|ooo classification when an NDR for this send was matched by the IMAP poller. NULL = no bounce detected (default).';
COMMENT ON COLUMN document_sends.bounce_reason IS
  'Phase 6: human-readable reason from the parsed NDR (e.g. "user not found"). NULL when not bounced.';
COMMENT ON COLUMN document_sends.bounce_detected_at IS
  'Phase 6: timestamp the cron worker detected this bounce. Drives the in-CRM notification firing once.';
