-- Migration 024: Fix face_embedding dimension (768 → 512)
-- Date: 2026-04-28
-- Purpose: Correct face_embedding dimension to match ArcFace (512-dim)
-- Issue: Migration 023 renamed embedding(768) to face_embedding, but ArcFace outputs 512-dim
-- Safety: No existing embedding data, safe to drop and recreate

-- ============================================
-- Part 1: Drop face_embedding column and recreate as 512-dim
-- ============================================

-- public schema
ALTER TABLE public.identities DROP COLUMN IF EXISTS face_embedding;
ALTER TABLE public.identities ADD COLUMN face_embedding VECTOR(512);

-- dev schema
ALTER TABLE dev.identities DROP COLUMN IF EXISTS face_embedding;
ALTER TABLE dev.identities ADD COLUMN face_embedding VECTOR(512);

-- ============================================
-- Part 2: Update comments
-- ============================================

COMMENT ON COLUMN public.identities.face_embedding IS 
'InsightFace ArcFace 512-dim embedding';

COMMENT ON COLUMN dev.identities.face_embedding IS 
'InsightFace ArcFace 512-dim embedding';

-- ============================================
-- Part 3: Recreate index for 512-dim
-- ============================================

-- Drop old index (if exists)
DROP INDEX IF EXISTS public.idx_identities_face_embedding;
DROP INDEX IF EXISTS dev.idx_dev_identities_face_embedding;

-- Create new index for 512-dim
CREATE INDEX idx_identities_face_embedding 
ON public.identities USING ivfflat (face_embedding vector_cosine_ops)
WITH (lists = 100);

CREATE INDEX idx_dev_identities_face_embedding 
ON dev.identities USING ivfflat (face_embedding vector_cosine_ops)
WITH (lists = 100);

-- ============================================
-- Verification
-- ============================================

DO $$ 
DECLARE
    dim INTEGER;
BEGIN
    -- Check public schema
    SELECT character_maximum_length INTO dim
    FROM information_schema.columns
    WHERE table_schema = 'public' 
    AND table_name = 'identities' 
    AND column_name = 'face_embedding';
    
    -- Note: vector type doesn't report dimension in information_schema
    -- We'll check via pg_attribute instead
    
    RAISE NOTICE 'Migration 024: face_embedding recreated as VECTOR(512) in public.identities';
    RAISE NOTICE 'Migration 024: face_embedding recreated as VECTOR(512) in dev.identities';
END $$;