-- chatSessions: one row per chat request, survives page reloads
CREATE TABLE IF NOT EXISTS chatSessions (
  id          INT AUTO_INCREMENT PRIMARY KEY,
  sessionId   VARCHAR(64) NOT NULL UNIQUE,
  agentId     INT NOT NULL DEFAULT 1,
  status      ENUM('running','done','error') NOT NULL DEFAULT 'running',
  userMessage TEXT NOT NULL,
  finalResponse TEXT,
  model       VARCHAR(128),
  totalTokens INT DEFAULT 0,
  processingTimeMs INT DEFAULT 0,
  errorMessage TEXT,
  createdAt   TIMESTAMP NOT NULL DEFAULT NOW(),
  updatedAt   TIMESTAMP NOT NULL DEFAULT NOW() ON UPDATE NOW(),
  INDEX chatSessions_status_idx (status),
  INDEX chatSessions_createdAt_idx (createdAt)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

-- chatEvents: one row per SSE event within a session
CREATE TABLE IF NOT EXISTS chatEvents (
  id          INT AUTO_INCREMENT PRIMARY KEY,
  sessionId   VARCHAR(64) NOT NULL,
  seq         INT NOT NULL DEFAULT 0,
  eventType   ENUM('thinking','tool_call','delta','done','error') NOT NULL,
  content     TEXT,
  toolName    VARCHAR(128),
  toolArgs    JSON,
  toolResult  TEXT,
  toolSuccess TINYINT(1),
  durationMs  INT,
  model       VARCHAR(128),
  usageJson   JSON,
  errorMsg    TEXT,
  createdAt   TIMESTAMP(3) NOT NULL DEFAULT NOW(3),
  INDEX chatEvents_sessionId_seq_idx (sessionId, seq)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
