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

export const CONVERSATIONS_TABLE = 'conversations';
export const CONVERSATION_CACHE_TABLE = 'conversation_cache';
export const CONVERSATION_LIST_CACHE_TABLE = 'conversation_list_cache';

export const CREATE_CONVERSATIONS_TABLE = `CREATE TABLE IF NOT EXISTS conversations (
  id TEXT PRIMARY KEY NOT NULL,
  participantId TEXT NOT NULL,
  lastMessageId TEXT,
  lastSeq INTEGER DEFAULT 0,
  unreadCount INTEGER DEFAULT 0,
  createdAt TEXT NOT NULL,
  updatedAt TEXT NOT NULL
)`;

export const CREATE_CONVERSATION_CACHE_TABLE = `CREATE TABLE IF NOT EXISTS conversation_cache (
  id TEXT PRIMARY KEY NOT NULL,
  data TEXT NOT NULL,
  updatedAt TEXT NOT NULL
)`;

export const CREATE_CONVERSATION_LIST_CACHE_TABLE = `CREATE TABLE IF NOT EXISTS conversation_list_cache (
  id TEXT PRIMARY KEY NOT NULL,
  data TEXT NOT NULL,
  updatedAt TEXT NOT NULL
)`;

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

    if (!columns.includes('lastSeq')) {
      await db.execAsync(`ALTER TABLE conversations ADD COLUMN lastSeq INTEGER DEFAULT 0`);
    }
  } catch (error) {
    console.error('[ConversationSchema] 迁移失败:', error);
  }
};