import 'package:drift/drift.dart';
import 'package:im_app/data/local/drift/tables/sounds.dart';
import 'package:im_app/data/local/drift/tables/tags.dart';
import 'package:im_app/data/local/drift/tables/favorite_details.dart';
import 'package:im_app/data/local/drift/tables/pending_friend_request_histories.dart';
import 'package:im_app/data/local/drift/tables/favorites.dart';
import 'package:im_app/data/local/drift/tables/message.dart';
import 'package:im_app/data/local/drift/tables/recent_mini_apps.dart';
import 'package:im_app/data/local/drift/tables/groups.dart';
import 'package:im_app/data/local/drift/tables/favorite_mini_apps.dart';
import 'package:im_app/data/local/drift/tables/discover_mini_apps.dart';
import 'package:im_app/data/local/drift/tables/chat_categories.dart';
import 'package:im_app/data/local/drift/tables/api_retries.dart';
import 'package:im_app/data/local/drift/tables/chat_bots.dart';
import 'package:im_app/data/local/drift/tables/user_request_histories.dart';
import 'package:im_app/data/local/drift/tables/workspaces.dart';
import 'package:im_app/data/local/drift/tables/users.dart';
import 'package:im_app/data/local/drift/tables/explore_mini_apps.dart';
import 'package:im_app/data/local/drift/tables/call_logs.dart';
import 'package:im_app/data/local/drift/tables/chats.dart';

part 'app_database.g.dart';

@DriftDatabase(
  tables: [
    Favorites,
    Sounds,
    Tags,
    PendingFriendRequestHistories,
    Messages,
    RecentMiniApps,
    ApiRetries,
    Groups,
    FavoriteMiniApps,
    DiscoverMiniApps,
    ChatCategories,
    ChatBots,
    FavoriteDetails,
    UserRequestHistories,
    Workspaces,
    Users,
    ExploreMiniApps,
    CallLogs,
    Chats,
  ],
) //update mapping here
class AppDatabase extends _$AppDatabase {
  static Map<Type, TableInfo> getTableRegistry(GeneratedDatabase database) {
    if (database is! AppDatabase) {
      return {};
    }
    return {
      DriftSound: database.sounds,
      DriftTag: database.tags,
      DriftFavoriteDetail: database.favoriteDetails,
      DriftPendingFriendRequestHistory: database.pendingFriendRequestHistories,
      DriftFavorite: database.favorites,
      DriftMessage: database.messages,
      DriftRecentMiniApp: database.recentMiniApps,
      DriftGroup: database.groups,
      DriftFavoriteMiniApp: database.favoriteMiniApps,
      DriftDiscoverMiniApp: database.discoverMiniApps,
      DriftChatCategory: database.chatCategories,
      DriftApiRetry: database.apiRetries,
      DriftChatBot: database.chatBots,
      DriftUserRequestHistory: database.userRequestHistories,
      DriftWorkspace: database.workspaces,
      DriftUser: database.users,
      DriftExploreMiniApp: database.exploreMiniApps,
      DriftCallLog: database.callLogs,
      DriftChat: database.chats,
    };
  }

  AppDatabase(super.e);

  //升级数据库用此版本号
  @override
  int get schemaVersion => 2;

  @override
  MigrationStrategy get migration {
    return MigrationStrategy(
      onCreate: (m) async {
        await m.createAll();
      },
      onUpgrade: (m, from, to) async {
        // Create any new tables that don't exist yet
        for (final table in allTables) {
          final existingTables = await m.database
              .customSelect(
                "SELECT name FROM sqlite_master WHERE type='table' AND name='${table.actualTableName}'",
              )
              .get();

          if (existingTables.isEmpty) {
            await m.createTable(table);
            continue;
          }

          // Auto-detect and add missing columns
          final existingColumns = await m.database
              .customSelect('PRAGMA table_info(${table.actualTableName})')
              .get();
          final existingNames = existingColumns
              .map((r) => r.data['name'] as String)
              .toSet();

          for (final column in table.$columns) {
            if (!existingNames.contains(column.name)) {
              await m.addColumn(table, column);
            }
          }
        }
      },
    );
  }
}
