-- Smart-archive feature - add columns that capture WHO archived a client,
-- WHY, and WHAT decisions they made along the way (for the restore
-- wizard to attempt reversal).
--
-- archived_at already exists (since the original schema). The three new
-- columns are all nullable and default-friendly so existing archived
-- rows backfill cleanly: their reason/metadata stays NULL, which the
-- service treats as "legacy archive (no smart-archive metadata)".

ALTER TABLE clients ADD COLUMN IF NOT EXISTS archived_by text;
ALTER TABLE clients ADD COLUMN IF NOT EXISTS archive_reason text;
ALTER TABLE clients ADD COLUMN IF NOT EXISTS archive_metadata jsonb;

-- archived_by FK is SET NULL on user delete so the audit trail outlives
-- staff turnover. Not VALID immediately to keep the lock window short;
-- VALIDATE after the column is in place.
DO $$
BEGIN
  IF NOT EXISTS (
    SELECT 1 FROM pg_constraint WHERE conname = 'clients_archived_by_fk'
  ) THEN
    ALTER TABLE clients
      ADD CONSTRAINT clients_archived_by_fk
      FOREIGN KEY (archived_by) REFERENCES "user"(id)
      ON DELETE SET NULL
      NOT VALID;
  END IF;
END$$;

ALTER TABLE clients VALIDATE CONSTRAINT clients_archived_by_fk;
