-- ============================================
-- MIGRACIÓN 004: Esquema de Glosario (tes_content)
-- ============================================
-- TICKET-007: Schema de BD para glosario
-- Crea la tabla glossary_terms en tes_content.
-- Reutiliza tes_content.content_status para estado.
--

-- Schema tes_content ya existe (003); content_status ya existe.

-- ============================================
-- TABLA: glossary_terms
-- Propósito: Términos del glosario médico (farmacológico, anatómico, clínico, procedural)
-- ============================================
CREATE TABLE IF NOT EXISTS tes_content.glossary_terms (
    id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
    term VARCHAR(200) NOT NULL,
    abbreviation VARCHAR(50),
    category VARCHAR(50) NOT NULL,
    definition TEXT NOT NULL,
    context VARCHAR(500),
    examples TEXT[],
    related_terms UUID[],
    source VARCHAR(200),
    status tes_content.content_status NOT NULL DEFAULT 'draft',

    created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    created_by UUID NOT NULL,
    updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    updated_by UUID,

    CONSTRAINT chk_glossary_category CHECK (category IN ('pharmaceutical', 'anatomical', 'clinical', 'procedural'))
);

-- Índices
CREATE INDEX IF NOT EXISTS idx_glossary_terms_category ON tes_content.glossary_terms(category);
CREATE INDEX IF NOT EXISTS idx_glossary_terms_status ON tes_content.glossary_terms(status);
CREATE INDEX IF NOT EXISTS idx_glossary_terms_term_lower ON tes_content.glossary_terms(LOWER(term));
CREATE UNIQUE INDEX IF NOT EXISTS idx_glossary_terms_term_category ON tes_content.glossary_terms(LOWER(term), category);
CREATE INDEX IF NOT EXISTS idx_glossary_terms_updated_at ON tes_content.glossary_terms(updated_at);
-- Búsqueda full-text en term y definition
CREATE INDEX IF NOT EXISTS idx_glossary_terms_fts ON tes_content.glossary_terms
    USING GIN (to_tsvector('spanish', term || ' ' || COALESCE(definition, '')));

-- Función updated_at en tes_content (idempotente)
CREATE OR REPLACE FUNCTION tes_content.update_updated_at_column()
RETURNS TRIGGER AS $$
BEGIN
  NEW.updated_at = NOW();
  RETURN NEW;
END;
$$ LANGUAGE plpgsql;

CREATE TRIGGER update_glossary_terms_updated_at
    BEFORE UPDATE ON tes_content.glossary_terms
    FOR EACH ROW
    EXECUTE FUNCTION tes_content.update_updated_at_column();

-- Comentarios
COMMENT ON TABLE tes_content.glossary_terms IS 'Términos del glosario médico (farmacológico, anatómico, clínico, procedural)';
