-- Audit-final v2 follow-up: document_sends.sent_by_user_id was a free-text
-- column with no FK. If a user is hard-deleted (rare; we soft-delete), an
-- orphan id remained without any ON DELETE handling. Add the FK with
-- SET NULL semantics so the audit row keeps recipient + timestamp + body
-- even when the originating user is removed.

-- Drop the NOT NULL so SET NULL is legal.
ALTER TABLE document_sends
  ALTER COLUMN sent_by_user_id DROP NOT NULL;

-- Defensive: if any historical rows have sent_by_user_id values that don't
-- match an existing user (dev-only), null them out so the FK can attach.
UPDATE document_sends
SET sent_by_user_id = NULL
WHERE sent_by_user_id IS NOT NULL
  AND sent_by_user_id NOT IN (SELECT id FROM "user");

ALTER TABLE document_sends
  ADD CONSTRAINT document_sends_sent_by_user_id_user_id_fk
    FOREIGN KEY (sent_by_user_id) REFERENCES "user"(id) ON DELETE SET NULL;

-- Index `idx_ds_sent_by` is created earlier in 0037_missing_fk_indexes.sql
-- (also IF NOT EXISTS so re-running is a no-op). Kept here as a comment
-- reference so a future maintainer reading just this migration knows the
-- index exists rather than thinking it was forgotten.
