-- Add archive support columns to contact_submissions
ALTER TABLE contact_submissions
  ADD COLUMN archived_at timestamp with time zone,
  ADD COLUMN archived_by uuid REFERENCES auth.users(id);

-- Add comments for clarity
COMMENT ON COLUMN contact_submissions.archived_at IS 'Timestamp when submission was archived (soft deleted)';
COMMENT ON COLUMN contact_submissions.archived_by IS 'User who archived this submission';

-- Index for performance on archived queries
CREATE INDEX idx_contact_submissions_archived ON contact_submissions(archived_at) 
  WHERE archived_at IS NOT NULL;

-- Add FK constraint to ensure email threads are deleted with submission (cascade)
ALTER TABLE contact_email_threads
  ADD CONSTRAINT fk_submission_cascade
  FOREIGN KEY (submission_id)
  REFERENCES contact_submissions(id)
  ON DELETE CASCADE;

-- Add comment on constraint
COMMENT ON CONSTRAINT fk_submission_cascade ON contact_email_threads IS 
  'Cascade delete email threads when parent submission is deleted';

-- Allow moderators to DELETE contact submissions (hard delete with MFA)
CREATE POLICY "Moderators can delete contact submissions" ON contact_submissions
  FOR DELETE
  TO authenticated
  USING (
    is_moderator(auth.uid()) AND has_aal2()
  );