-- Agent 会话与消息表。

CREATE TABLE IF NOT EXISTS agent_session (
    id BIGSERIAL PRIMARY KEY,
    session_code VARCHAR(100) NOT NULL,
    agent_id BIGINT NOT NULL,
    workflow_run_id BIGINT,
    title VARCHAR(200),
    status VARCHAR(50) NOT NULL DEFAULT 'ACTIVE',
    metadata_json JSONB NOT NULL DEFAULT '{}'::jsonb,
    version INTEGER NOT NULL DEFAULT 1,
    create_time TIMESTAMP,
    update_time TIMESTAMP,
    remark VARCHAR(500) DEFAULT '',
    create_by VARCHAR(64),
    update_by VARCHAR(64),
    CONSTRAINT uk_agent_session_code UNIQUE (session_code),
    CONSTRAINT fk_agent_session_agent_id FOREIGN KEY (agent_id) REFERENCES agent_definition (id),
    CONSTRAINT fk_agent_session_run_id FOREIGN KEY (workflow_run_id) REFERENCES workflow_run (id)
);

CREATE TABLE IF NOT EXISTS agent_message (
    id BIGSERIAL PRIMARY KEY,
    session_id BIGINT NOT NULL,
    role VARCHAR(50) NOT NULL,
    content TEXT NOT NULL,
    citation_json JSONB NOT NULL DEFAULT '[]'::jsonb,
    token_count INTEGER,
    version INTEGER NOT NULL DEFAULT 1,
    create_time TIMESTAMP,
    update_time TIMESTAMP,
    remark VARCHAR(500) DEFAULT '',
    create_by VARCHAR(64),
    update_by VARCHAR(64),
    CONSTRAINT fk_agent_message_session_id FOREIGN KEY (session_id) REFERENCES agent_session (id)
);

CREATE INDEX IF NOT EXISTS idx_agent_session_agent_id ON agent_session (agent_id);
CREATE INDEX IF NOT EXISTS idx_agent_session_status ON agent_session (status);
CREATE INDEX IF NOT EXISTS idx_agent_message_session_id ON agent_message (session_id);
CREATE INDEX IF NOT EXISTS idx_agent_message_role ON agent_message (role);

COMMENT ON TABLE agent_session IS 'Agent会话表';
COMMENT ON TABLE agent_message IS 'Agent消息表';
