-- ============================================
-- SCHEMA LOG - Sistema TZZR
-- Log inmutable de mensajes
-- ============================================

DROP SCHEMA IF EXISTS log CASCADE;
CREATE SCHEMA log;

-- Extensiones
CREATE EXTENSION IF NOT EXISTS pgcrypto;

-- Tipos
CREATE TYPE log.actor_type AS ENUM ('user', 'agent', 'orchestrator', 'system', 'tool');

-- Tabla principal
CREATE TABLE log.messages (
    id              BIGSERIAL PRIMARY KEY,
    hash            CHAR(64) UNIQUE NOT NULL,
    session_hash    CHAR(64) NOT NULL,
    sender_type     log.actor_type NOT NULL,
    sender_id       CHAR(64) NOT NULL,
    receiver_type   log.actor_type NOT NULL,
    receiver_id     CHAR(64) NOT NULL,
    leader_id       CHAR(64),
    role            TEXT,
    content         TEXT NOT NULL,
    attachments     JSONB DEFAULT '{}',
    prev_hash       CHAR(64),
    context_hashes  CHAR(64)[] DEFAULT '{}',
    hashtags        CHAR(64)[] DEFAULT '{}',
    created_at      TIMESTAMPTZ DEFAULT NOW()
);

-- Índices
CREATE INDEX idx_messages_session ON log.messages(session_hash);
CREATE INDEX idx_messages_sender ON log.messages(sender_id);
CREATE INDEX idx_messages_receiver ON log.messages(receiver_id);
CREATE INDEX idx_messages_prev ON log.messages(prev_hash);
CREATE INDEX idx_messages_created ON log.messages(created_at);
CREATE INDEX idx_messages_hashtags ON log.messages USING gin(hashtags);

-- Función SHA256
CREATE OR REPLACE FUNCTION log.sha256(data TEXT) RETURNS CHAR(64) AS $$
BEGIN
    RETURN encode(digest(data, 'sha256'), 'hex');
END;
$$ LANGUAGE plpgsql IMMUTABLE;

-- Protección: no UPDATE
CREATE OR REPLACE FUNCTION log.prevent_update() RETURNS TRIGGER AS $$
BEGIN
    RAISE EXCEPTION 'UPDATE no permitido en log.messages';
END;
$$ LANGUAGE plpgsql;

-- Protección: no DELETE
CREATE OR REPLACE FUNCTION log.prevent_delete() RETURNS TRIGGER AS $$
BEGIN
    RAISE EXCEPTION 'DELETE no permitido en log.messages';
END;
$$ LANGUAGE plpgsql;

-- Triggers de protección
CREATE TRIGGER protect_update BEFORE UPDATE ON log.messages
    FOR EACH ROW EXECUTE FUNCTION log.prevent_update();

CREATE TRIGGER protect_delete BEFORE DELETE ON log.messages
    FOR EACH ROW EXECUTE FUNCTION log.prevent_delete();

-- Permisos
GRANT USAGE ON SCHEMA log TO tzzr;
GRANT SELECT, INSERT ON log.messages TO tzzr;
GRANT USAGE ON SEQUENCE log.messages_id_seq TO tzzr;

-- Verificación
SELECT 'Schema log creado' as status;
