/** Native SQLite database name for Capacitor mobile shells. */
export const MOBILE_SQLITE_DATABASE_NAME = 'metoyou';

/** Bump when adding DDL statements; stored in meta table. */
export const MOBILE_SQLITE_SCHEMA_VERSION = 3;

const META_SCHEMA_VERSION_KEY = 'mobile_sqlite_schema_version';

/** DDL mirrored from Electron TypeORM entities under `electron/entities/`. */
export function buildMobileSqliteSchemaStatements(): string[] {
  return [
    `CREATE TABLE IF NOT EXISTS messages (
      id TEXT PRIMARY KEY NOT NULL,
      roomId TEXT NOT NULL,
      ownerUserId TEXT,
      channelId TEXT,
      senderId TEXT NOT NULL,
      senderName TEXT NOT NULL,
      content TEXT NOT NULL,
      timestamp INTEGER NOT NULL,
      editedAt INTEGER,
      isDeleted INTEGER NOT NULL DEFAULT 0,
      replyToId TEXT,
      linkMetadata TEXT,
      kind TEXT,
      systemEvent TEXT,
      revision INTEGER NOT NULL DEFAULT 0,
      headHash TEXT
    )`,
    'CREATE INDEX IF NOT EXISTS idx_messages_room_id ON messages(roomId)',
    'CREATE INDEX IF NOT EXISTS idx_messages_timestamp ON messages(timestamp)',
    `CREATE TABLE IF NOT EXISTS users (
      id TEXT PRIMARY KEY NOT NULL,
      oderId TEXT,
      username TEXT,
      displayName TEXT,
      description TEXT,
      profileUpdatedAt INTEGER,
      avatarUrl TEXT,
      avatarHash TEXT,
      avatarMime TEXT,
      avatarUpdatedAt INTEGER,
      status TEXT,
      role TEXT,
      joinedAt INTEGER,
      peerId TEXT,
      isOnline INTEGER NOT NULL DEFAULT 0,
      isAdmin INTEGER NOT NULL DEFAULT 0,
      isRoomOwner INTEGER NOT NULL DEFAULT 0,
      voiceState TEXT,
      screenShareState TEXT,
      homeSignalServerUrl TEXT
    )`,
    `CREATE TABLE IF NOT EXISTS rooms (
      id TEXT PRIMARY KEY NOT NULL,
      name TEXT NOT NULL,
      description TEXT,
      topic TEXT,
      hostId TEXT NOT NULL,
      password TEXT,
      hasPassword INTEGER NOT NULL DEFAULT 0,
      isPrivate INTEGER NOT NULL DEFAULT 0,
      createdAt INTEGER NOT NULL,
      userCount INTEGER NOT NULL DEFAULT 0,
      maxUsers INTEGER,
      icon TEXT,
      iconUpdatedAt INTEGER,
      slowModeInterval INTEGER NOT NULL DEFAULT 0,
      sourceId TEXT,
      sourceName TEXT,
      sourceUrl TEXT
    )`,
    'CREATE INDEX IF NOT EXISTS idx_rooms_created_at ON rooms(createdAt)',
    `CREATE TABLE IF NOT EXISTS reactions (
      id TEXT PRIMARY KEY NOT NULL,
      messageId TEXT NOT NULL,
      oderId TEXT,
      userId TEXT,
      emoji TEXT NOT NULL,
      timestamp INTEGER NOT NULL
    )`,
    'CREATE INDEX IF NOT EXISTS idx_reactions_message_id ON reactions(messageId)',
    `CREATE TABLE IF NOT EXISTS bans (
      oderId TEXT NOT NULL,
      roomId TEXT NOT NULL,
      userId TEXT,
      bannedBy TEXT NOT NULL,
      displayName TEXT,
      reason TEXT,
      expiresAt INTEGER,
      timestamp INTEGER NOT NULL,
      PRIMARY KEY (oderId, roomId)
    )`,
    'CREATE INDEX IF NOT EXISTS idx_bans_room_id ON bans(roomId)',
    `CREATE TABLE IF NOT EXISTS attachments (
      id TEXT PRIMARY KEY NOT NULL,
      messageId TEXT NOT NULL,
      filename TEXT NOT NULL,
      size INTEGER NOT NULL,
      mime TEXT NOT NULL,
      isImage INTEGER NOT NULL DEFAULT 0,
      uploaderPeerId TEXT,
      filePath TEXT,
      savedPath TEXT
    )`,
    'CREATE INDEX IF NOT EXISTS idx_attachments_message_id ON attachments(messageId)',
    `CREATE TABLE IF NOT EXISTS custom_emojis (
      id TEXT PRIMARY KEY NOT NULL,
      name TEXT NOT NULL,
      creatorUserId TEXT NOT NULL,
      dataUrl TEXT NOT NULL,
      hash TEXT NOT NULL,
      mime TEXT NOT NULL,
      size INTEGER NOT NULL,
      createdAt INTEGER NOT NULL,
      updatedAt INTEGER NOT NULL
    )`,
    'CREATE INDEX IF NOT EXISTS idx_custom_emojis_updated_at ON custom_emojis(updatedAt)',
    `CREATE TABLE IF NOT EXISTS meta (
      key TEXT PRIMARY KEY NOT NULL,
      value TEXT
    )`,
    `CREATE TABLE IF NOT EXISTS push_device_tokens (
      id TEXT PRIMARY KEY NOT NULL,
      userId TEXT NOT NULL,
      platform TEXT NOT NULL,
      token TEXT NOT NULL,
      updatedAt INTEGER NOT NULL
    )`,
    'CREATE INDEX IF NOT EXISTS idx_push_device_tokens_user_id ON push_device_tokens(userId)',
    `INSERT OR REPLACE INTO meta (key, value) VALUES ('${META_SCHEMA_VERSION_KEY}', '${MOBILE_SQLITE_SCHEMA_VERSION}')`
  ];
}

const SCHEMA_V2_MESSAGE_COLUMNS = [
  'ALTER TABLE messages ADD COLUMN linkMetadata TEXT',
  'ALTER TABLE messages ADD COLUMN kind TEXT',
  'ALTER TABLE messages ADD COLUMN systemEvent TEXT'
];
const SCHEMA_V3_MESSAGE_COLUMNS = ['ALTER TABLE messages ADD COLUMN revision INTEGER NOT NULL DEFAULT 0', 'ALTER TABLE messages ADD COLUMN headHash TEXT'];

/** Returns DDL statements that still need to run for the stored schema version. */
export function resolveMobileSqliteMigrationStatements(storedVersion: number): string[] {
  if (storedVersion >= MOBILE_SQLITE_SCHEMA_VERSION) {
    return [];
  }

  if (storedVersion <= 0) {
    return buildMobileSqliteSchemaStatements();
  }

  const statements: string[] = [];

  if (storedVersion < 2) {
    statements.push(...SCHEMA_V2_MESSAGE_COLUMNS);
    statements.push(`INSERT OR REPLACE INTO meta (key, value) VALUES ('${META_SCHEMA_VERSION_KEY}', '2')`);
  }

  if (storedVersion < 3) {
    statements.push(...SCHEMA_V3_MESSAGE_COLUMNS);
    statements.push(`INSERT OR REPLACE INTO meta (key, value) VALUES ('${META_SCHEMA_VERSION_KEY}', '3')`);
  }

  return statements;
}
