import type { SQLiteDatabase } from 'expo-sqlite';

export const MESSAGES_TABLE = 'messages';

export const CREATE_MESSAGES_TABLE = `CREATE TABLE IF NOT EXISTS messages (
  id TEXT PRIMARY KEY NOT NULL,
  conversationId TEXT NOT NULL,
  senderId TEXT NOT NULL,
  content TEXT,
  type TEXT DEFAULT 'text',
  isRead INTEGER DEFAULT 0,
  createdAt TEXT NOT NULL,
  seq INTEGER DEFAULT 0,
  status TEXT DEFAULT 'normal',
  segments TEXT
)`;

export const CREATE_MESSAGES_INDEXES = [
  `CREATE INDEX IF NOT EXISTS idx_messages_conversationId ON messages(conversationId)`,
  `CREATE INDEX IF NOT EXISTS idx_messages_seq ON messages(seq)`,
  `CREATE INDEX IF NOT EXISTS idx_messages_conversation_seq ON messages(conversationId, seq)`,
];

export const MIGRATE_MESSAGES_TABLE = async (db: SQLiteDatabase): Promise<void> => {
  try {
    const tableInfo = await db.getAllAsync<{ name: string }>(`PRAGMA table_info(messages)`);
    const columns = tableInfo.map(col => col.name);

    if (!columns.includes('seq')) {
      await db.execAsync(`ALTER TABLE messages ADD COLUMN seq INTEGER DEFAULT 0`);
    }
    if (!columns.includes('status')) {
      await db.execAsync(`ALTER TABLE messages ADD COLUMN status TEXT DEFAULT 'normal'`);
    }
    if (!columns.includes('segments')) {
      await db.execAsync(`ALTER TABLE messages ADD COLUMN segments TEXT`);
    }
  } catch (error) {
    console.error('[MessageSchema] 迁移失败:', error);
  }
};