-- Migration: 026_create_file_identities_table.sql (Fixed v2)
-- Date: 2026-04-28
-- Version: V4.0
-- Purpose: Create file_identities table for N:N relationship
-- Note: Uses videos table, no timestamp in face_detections

BEGIN;

-- 1. Create file_identities table
CREATE TABLE IF NOT EXISTS file_identities (
    id BIGSERIAL PRIMARY KEY,
    file_uuid VARCHAR(255) NOT NULL,
    identity_id BIGINT NOT NULL,
    face_count INTEGER DEFAULT 0,
    speaker_count INTEGER DEFAULT 0,
    first_appearance DOUBLE PRECISION,
    last_appearance DOUBLE PRECISION,
    confidence DOUBLE PRECISION DEFAULT 0.0,
    created_at TIMESTAMPTZ DEFAULT NOW(),
    updated_at TIMESTAMPTZ DEFAULT NOW(),
    
    CONSTRAINT fk_file_identities_video 
        FOREIGN KEY (file_uuid) 
        REFERENCES videos(uuid) 
        ON DELETE CASCADE,
    
    CONSTRAINT fk_file_identities_identity 
        FOREIGN KEY (identity_id) 
        REFERENCES identities(id) 
        ON DELETE CASCADE,
    
    CONSTRAINT uq_file_identities 
        UNIQUE (file_uuid, identity_id)
);

-- 2. Create indexes
CREATE INDEX IF NOT EXISTS idx_file_identities_file_uuid ON file_identities(file_uuid);
CREATE INDEX IF NOT EXISTS idx_file_identities_identity_id ON file_identities(identity_id);
CREATE INDEX IF NOT EXISTS idx_file_identities_confidence ON file_identities(confidence DESC);

-- 3. Populate from existing face_detections (identity_id exists)
-- Note: face_detections doesn't have timestamp, skip first/last_appearance
INSERT INTO file_identities (file_uuid, identity_id, face_count, confidence)
SELECT 
    fd.file_uuid,
    fd.identity_id,
    COUNT(*) AS face_count,
    AVG(fd.confidence) AS confidence
FROM face_detections fd
WHERE fd.identity_id IS NOT NULL
GROUP BY fd.file_uuid, fd.identity_id
ON CONFLICT (file_uuid, identity_id) DO NOTHING;

COMMIT;