-- =============================================================================
-- Migration: Add hash columns for field-level PII encryption
--
-- This migration adds deterministic HMAC-SHA256 hash columns alongside
-- encrypted PII fields to support indexed lookups (WHERE / UNIQUE).
--
-- The original email/phone columns will hold encrypted ciphertext after
-- the backfill script runs. Uniqueness shifts to the hash columns.
-- =============================================================================

-- ---------- User ----------

-- Drop existing unique constraints on plaintext columns
-- These will be replaced by unique constraints on hash columns
ALTER TABLE "User" DROP CONSTRAINT IF EXISTS "User_email_key";
ALTER TABLE "User" DROP CONSTRAINT IF EXISTS "User_phone_key";

-- Add hash columns
ALTER TABLE "User" ADD COLUMN "emailHash" TEXT;
ALTER TABLE "User" ADD COLUMN "phoneHash" TEXT;

-- Unique indexes on hash columns (replace the old plaintext unique constraints)
CREATE UNIQUE INDEX "User_emailHash_key" ON "User"("emailHash");
CREATE UNIQUE INDEX "User_phoneHash_key" ON "User"("phoneHash");

-- ---------- Lead ----------

-- Add hash columns
ALTER TABLE "Lead" ADD COLUMN "phoneHash" TEXT;
ALTER TABLE "Lead" ADD COLUMN "emailHash" TEXT;

-- Non-unique indexes for Lead hash columns (leads can share phone/email)
CREATE INDEX "Lead_phoneHash_idx" ON "Lead"("phoneHash");
CREATE INDEX "Lead_emailHash_idx" ON "Lead"("emailHash");
