-- 기존 message_buffer 데이터를 새 conversation 테이블로 마이그레이션
-- 대상: 2명 사용자 (telegram_id: 7265981403, 821596605)

-- 1. 사용자 7265981403 테이블 생성
CREATE TABLE IF NOT EXISTS conv_7265981403 (
  id INTEGER PRIMARY KEY AUTOINCREMENT,
  role TEXT NOT NULL CHECK(role IN ('user', 'assistant')),
  content TEXT NOT NULL,
  tool_calls TEXT,
  tool_results TEXT,
  created_at DATETIME DEFAULT CURRENT_TIMESTAMP
);

CREATE INDEX IF NOT EXISTS idx_conv_7265981403_created ON conv_7265981403(created_at DESC);

-- 2. 사용자 821596605 테이블 생성
CREATE TABLE IF NOT EXISTS conv_821596605 (
  id INTEGER PRIMARY KEY AUTOINCREMENT,
  role TEXT NOT NULL CHECK(role IN ('user', 'assistant')),
  content TEXT NOT NULL,
  tool_calls TEXT,
  tool_results TEXT,
  created_at DATETIME DEFAULT CURRENT_TIMESTAMP
);

CREATE INDEX IF NOT EXISTS idx_conv_821596605_created ON conv_821596605(created_at DESC);

-- 3. 사용자 7265981403 메시지 복사 (role: bot -> assistant)
INSERT INTO conv_7265981403 (role, content, created_at)
SELECT
  CASE WHEN role = 'bot' THEN 'assistant' ELSE 'user' END,
  message,
  created_at
FROM message_buffer
WHERE user_id = 3
ORDER BY created_at ASC;

-- 4. 사용자 821596605 메시지 복사
INSERT INTO conv_821596605 (role, content, created_at)
SELECT
  CASE WHEN role = 'bot' THEN 'assistant' ELSE 'user' END,
  message,
  created_at
FROM message_buffer
WHERE user_id = 1
ORDER BY created_at ASC;

-- 5. conversation_tables 메타 테이블에 등록
INSERT OR REPLACE INTO conversation_tables (telegram_id, table_name, message_count, last_message_at)
SELECT
  '7265981403',
  'conv_7265981403',
  (SELECT COUNT(*) FROM conv_7265981403),
  (SELECT MAX(created_at) FROM conv_7265981403);

INSERT OR REPLACE INTO conversation_tables (telegram_id, table_name, message_count, last_message_at)
SELECT
  '821596605',
  'conv_821596605',
  (SELECT COUNT(*) FROM conv_821596605),
  (SELECT MAX(created_at) FROM conv_821596605);
