ALTER TABLE DOC.doc_embedding
    DROP CONSTRAINT IF EXISTS ck_doc_embedding_dimensions_positive;

ALTER TABLE DOC.doc_embedding
    ADD CONSTRAINT ck_doc_embedding_dimensions_positive
    CHECK (embedding_dimensions IS NULL OR embedding_dimensions > 0);

DO $$
BEGIN
    IF NOT EXISTS (
        SELECT 1
        FROM pg_constraint
        WHERE conname = 'uq_doc_embedding_representation_model'
          AND conrelid = 'doc.doc_embedding'::regclass
    ) AND NOT EXISTS (
        SELECT 1
        FROM pg_class c
        JOIN pg_namespace n ON n.oid = c.relnamespace
        WHERE n.nspname = 'doc'
          AND c.relname = 'uq_doc_embedding_representation_model'
    ) THEN
        ALTER TABLE DOC.doc_embedding
            ADD CONSTRAINT uq_doc_embedding_representation_model
            UNIQUE (representation_id, model_id);
    END IF;
END $$;

COMMENT ON TABLE DOC.doc_embedding IS
'Option A multi-model embedding storage. Embeddings of different lengths may coexist in one table. Semantic search must always filter by model_id and embedding_dimensions.';

COMMENT ON COLUMN DOC.doc_embedding.embedding_dimensions IS
'Resolved dimension of the stored embedding. Used for validation, filtering, and model-specific vector casts.';

COMMENT ON COLUMN DOC.doc_embedding.embedding_vector IS
'Generic pgvector column without fixed dimension. Create per-model partial expression indexes with a fixed cast, e.g. ((embedding_vector::public.vector(1024)) vector_cosine_ops).';

-- Recommended partial ANN index pattern for active models:
-- CREATE INDEX idx_doc_embedding_<model_key>_hnsw
--   ON DOC.doc_embedding USING hnsw ((embedding_vector::public.vector(<DIMENSIONS>)) vector_cosine_ops)
--   WHERE model_id = '<MODEL_UUID>'::uuid
--     AND embedding_status = 'COMPLETED';
--
-- If you use inner product or euclidean distance for a model, pick the matching operator class:
--   vector_ip_ops
--   vector_l2_ops
