-- Migration: 027_add_identity_id_to_face_detections.sql
-- Date: 2026-04-28
-- Version: V4.0
-- Purpose: Add identity_id foreign key to face_detections for direct binding

BEGIN;

-- 1. Add identity_id column (if not exists)
DO $$ 
BEGIN
    IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name = 'face_detections' AND column_name = 'identity_id') THEN
        ALTER TABLE face_detections ADD COLUMN identity_id BIGINT;
    END IF;
END $$;

-- 2. Add foreign key constraint
ALTER TABLE face_detections 
DROP CONSTRAINT IF EXISTS fk_face_detections_identity,
ADD CONSTRAINT fk_face_detections_identity 
    FOREIGN KEY (identity_id) 
    REFERENCES identities(id) 
    ON DELETE SET NULL;

-- 3. Create index for identity queries
CREATE INDEX IF NOT EXISTS idx_face_detections_identity_id ON face_detections(identity_id) 
    WHERE identity_id IS NOT NULL;

-- 4. Create index for candidate queries (unregistered faces)
CREATE INDEX IF NOT EXISTS idx_face_detections_candidates ON face_detections(confidence DESC) 
    WHERE identity_id IS NULL;

COMMIT;