-- Schema LOG para Context Manager
CREATE SCHEMA IF NOT EXISTS log;

CREATE TABLE IF NOT EXISTS log.messages (
    id BIGSERIAL PRIMARY KEY,
    hash CHAR(64) UNIQUE NOT NULL,
    session_hash CHAR(64) NOT NULL,
    thread_hash CHAR(64),
    owner_id CHAR(64),
    players_id CHAR(64)[],
    master_player CHAR(64),
    role TEXT NOT NULL,
    content TEXT NOT NULL,
    attachments JSONB DEFAULT '{}',
    prev_hash CHAR(64),
    hashtags CHAR(64)[],
    flag_id CHAR(64),
    master_item_id CHAR(64),
    item_id CHAR(64)[],
    loc_id CHAR(64),
    ambient JSONB,
    created_at TIMESTAMPTZ DEFAULT NOW()
);

CREATE TABLE IF NOT EXISTS log.message_refs (
    id BIGSERIAL PRIMARY KEY,
    message_hash CHAR(64) NOT NULL,
    ref_hash CHAR(64) NOT NULL,
    ref_type VARCHAR(20) NOT NULL,
    position INT,
    thread_hash CHAR(64)
);

CREATE INDEX IF NOT EXISTS idx_log_session ON log.messages(session_hash);
CREATE INDEX IF NOT EXISTS idx_log_thread ON log.messages(thread_hash);
CREATE INDEX IF NOT EXISTS idx_log_owner ON log.messages(owner_id);
CREATE INDEX IF NOT EXISTS idx_log_prev ON log.messages(prev_hash);
CREATE INDEX IF NOT EXISTS idx_log_created ON log.messages(created_at);
CREATE INDEX IF NOT EXISTS idx_refs_message ON log.message_refs(message_hash);
CREATE INDEX IF NOT EXISTS idx_refs_ref ON log.message_refs(ref_hash);

CREATE OR REPLACE FUNCTION log.prevent_modification() RETURNS TRIGGER AS $$
BEGIN
    RAISE EXCEPTION 'Log is immutable';
END;
$$ LANGUAGE plpgsql;

DROP TRIGGER IF EXISTS no_update_messages ON log.messages;
DROP TRIGGER IF EXISTS no_delete_messages ON log.messages;
CREATE TRIGGER no_update_messages BEFORE UPDATE ON log.messages FOR EACH ROW EXECUTE FUNCTION log.prevent_modification();
CREATE TRIGGER no_delete_messages BEFORE DELETE ON log.messages FOR EACH ROW EXECUTE FUNCTION log.prevent_modification();

DROP TRIGGER IF EXISTS no_update_refs ON log.message_refs;
DROP TRIGGER IF EXISTS no_delete_refs ON log.message_refs;
CREATE TRIGGER no_update_refs BEFORE UPDATE ON log.message_refs FOR EACH ROW EXECUTE FUNCTION log.prevent_modification();
CREATE TRIGGER no_delete_refs BEFORE DELETE ON log.message_refs FOR EACH ROW EXECUTE FUNCTION log.prevent_modification();

GRANT USAGE ON SCHEMA log TO architect;
GRANT SELECT, INSERT ON ALL TABLES IN SCHEMA log TO architect;
GRANT USAGE, SELECT ON ALL SEQUENCES IN SCHEMA log TO architect;
