-- Migration 019: Document application-layer column encryption intent
--
-- Column encryption is applied at the APPLICATION LAYER via EncryptionService
-- (src/services/EncryptionService.ts), NOT via SQL transforms in this migration.
--
-- WHY application-layer encryption:
--   - Key management is centralised in HashiCorp Vault (not in PostgreSQL)
--   - Key rotation does not require SQL migrations — only the Vault secret is updated
--   - The encrypted format (AES-256-CBC, IV:ciphertext, base64-encoded) is portable
--     and auditable outside of PostgreSQL
--   - Database dumps do not expose plaintext sensitive values even without TDE
--
-- COLUMNS ENCRYPTED by EncryptionService on write, decrypted on read:
--   credentials.secret_hash        — bcrypt hash of the client secret (Phase 1 rows)
--   credentials.vault_path         — Vault KV v2 path to the credential secret
--   webhook_subscriptions.vault_secret_path — Vault path for the HMAC signing secret
--   agent_did_keys.vault_key_path  — Vault path for the DID private key
--
-- BACKWARD COMPATIBILITY:
--   Existing rows written before this migration contain PLAINTEXT values.
--   EncryptionService.isEncrypted() detects whether a value is encrypted.
--   Plaintext values are used as-is on reads and re-written in encrypted form
--   on the next update (lazy migration strategy — no batch re-encryption needed).
--
-- VERIFICATION:
--   After key rotation or re-encryption: run GET /audit/verify and
--   GET /compliance/controls to confirm CC6.1 (Encryption at Rest) passes.

-- Marker table to record that this migration has been applied and to provide
-- an audit trail for the encryption rollout.
CREATE TABLE IF NOT EXISTS _encryption_migration_log (
  migrated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
  note        TEXT
);

INSERT INTO _encryption_migration_log (note)
VALUES (
  'Migration 019 applied: application-layer AES-256-CBC column encryption declared. '
  'Columns: credentials.secret_hash, credentials.vault_path, '
  'webhook_subscriptions.vault_secret_path, agent_did_keys.vault_key_path. '
  'Existing plaintext values will be re-encrypted on next read-write cycle.'
);
