import 'package:drift/drift.dart';
import 'package:im_app/data/local/drift/tables/favourites.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/pending_friend_request_histories.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/retries.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/chat_bots.dart';
import 'package:im_app/data/local/drift/tables/favourite_details.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: [Favourites,Sounds,Tags,PendingFriendRequestHistories,Messages,RecentMiniApps,Retries,Groups,FavoriteMiniApps,DiscoverMiniApps,ChatCategories,ChatBots,FavouriteDetails,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 {
      DriftFavourite: database.favourites,
      DriftSound: database.sounds,
      DriftTag: database.tags,
      DriftPendingFriendRequestHistory: database.pendingFriendRequestHistories,
      DriftMessage: database.messages,
      DriftRecentMiniApp: database.recentMiniApps,
      DriftRetry: database.retries,
      DriftGroup: database.groups,
      DriftFavoriteMiniApp: database.favoriteMiniApps,
      DriftDiscoverMiniApp: database.discoverMiniApps,
      DriftChatCategory: database.chatCategories,
      DriftChatBot: database.chatBots,
      DriftFavouriteDetail: database.favouriteDetails,
      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);
            }
          }
        }
      },
    );
  }


}
