CREATE TABLE ias_long_term_memories (
    id BIGSERIAL PRIMARY KEY,
    scope_key VARCHAR(768) NOT NULL,
    channel VARCHAR(64) NOT NULL,
    account_id VARCHAR(255) NOT NULL,
    from_user_id VARCHAR(255) NOT NULL,
    context_label TEXT,
    content TEXT NOT NULL,
    metadata TEXT NOT NULL DEFAULT '{}',
    created_at TIMESTAMP NOT NULL DEFAULT NOW(),
    updated_at TIMESTAMP NOT NULL DEFAULT NOW(),
    deleted_at TIMESTAMP
);

CREATE INDEX idx_ias_long_term_memories_scope_updated
    ON ias_long_term_memories(scope_key, updated_at DESC)
    WHERE deleted_at IS NULL;

CREATE TABLE ias_context_sessions (
    id BIGSERIAL PRIMARY KEY,
    scope_key VARCHAR(768) NOT NULL,
    channel VARCHAR(64) NOT NULL,
    account_id VARCHAR(255) NOT NULL,
    from_user_id VARCHAR(255) NOT NULL,
    context_label TEXT,
    started_at TIMESTAMP NOT NULL DEFAULT NOW(),
    last_message_at TIMESTAMP NOT NULL DEFAULT NOW(),
    ended_at TIMESTAMP,
    end_reason VARCHAR(64),
    summary TEXT
);

CREATE INDEX idx_ias_context_sessions_active
    ON ias_context_sessions(scope_key, started_at DESC)
    WHERE ended_at IS NULL;

CREATE INDEX idx_ias_context_sessions_ended
    ON ias_context_sessions(scope_key, ended_at DESC)
    WHERE ended_at IS NOT NULL;

CREATE TABLE ias_context_messages (
    id BIGSERIAL PRIMARY KEY,
    session_id BIGINT NOT NULL REFERENCES ias_context_sessions(id) ON DELETE CASCADE,
    role VARCHAR(32) NOT NULL,
    content TEXT NOT NULL,
    tool_call_id VARCHAR(255),
    tool_calls TEXT,
    created_at TIMESTAMP NOT NULL DEFAULT NOW()
);

CREATE INDEX idx_ias_context_messages_session
    ON ias_context_messages(session_id, id);

CREATE TABLE ias_context_summaries (
    id BIGSERIAL PRIMARY KEY,
    scope_key VARCHAR(768) NOT NULL,
    summary_type VARCHAR(32) NOT NULL,
    source_session_id BIGINT REFERENCES ias_context_sessions(id) ON DELETE SET NULL,
    content TEXT NOT NULL,
    started_at TIMESTAMP,
    ended_at TIMESTAMP,
    created_at TIMESTAMP NOT NULL DEFAULT NOW()
);

CREATE INDEX idx_ias_context_summaries_latest
    ON ias_context_summaries(scope_key, summary_type, created_at DESC);
