-- Audit-final v2 fix: document_sends FKs default to NO ACTION which means
-- a hard-delete of a referenced client/interest/berth/brochure either
-- silently blocks the parent delete OR (if a future cascade path is added)
-- nukes the send-out audit row. The audit trail must outlast its source -
-- recipient_email + document_kind + body_markdown + from_address are
-- already denormalized onto the row for exactly this purpose.
--
-- Switch every parent FK to ON DELETE SET NULL so the audit row keeps a
-- timestamp + email even when the source row is gone.

ALTER TABLE document_sends
  DROP CONSTRAINT IF EXISTS document_sends_client_id_clients_id_fk,
  DROP CONSTRAINT IF EXISTS document_sends_interest_id_interests_id_fk,
  DROP CONSTRAINT IF EXISTS document_sends_berth_id_berths_id_fk,
  DROP CONSTRAINT IF EXISTS document_sends_brochure_id_brochures_id_fk,
  DROP CONSTRAINT IF EXISTS document_sends_brochure_version_id_brochure_versions_id_fk;

ALTER TABLE document_sends
  ADD CONSTRAINT document_sends_client_id_clients_id_fk
    FOREIGN KEY (client_id) REFERENCES clients(id) ON DELETE SET NULL,
  ADD CONSTRAINT document_sends_interest_id_interests_id_fk
    FOREIGN KEY (interest_id) REFERENCES interests(id) ON DELETE SET NULL,
  ADD CONSTRAINT document_sends_berth_id_berths_id_fk
    FOREIGN KEY (berth_id) REFERENCES berths(id) ON DELETE SET NULL,
  ADD CONSTRAINT document_sends_brochure_id_brochures_id_fk
    FOREIGN KEY (brochure_id) REFERENCES brochures(id) ON DELETE SET NULL,
  ADD CONSTRAINT document_sends_brochure_version_id_brochure_versions_id_fk
    FOREIGN KEY (brochure_version_id) REFERENCES brochure_versions(id) ON DELETE SET NULL;
