import 'dart:io';
import 'package:drift/drift.dart';
import 'package:drift/native.dart';
import 'package:path_provider/path_provider.dart';
import 'package:path/path.dart' as p;
import 'tables.dart';
import 'converters/json_converter.dart';

part 'app_database.g.dart';

@DriftDatabase(tables: [Users, Cycles, Workouts, Quests])
class AppDatabase extends _$AppDatabase {
  AppDatabase() : super(_openConnection());

  @override
  int get schemaVersion => 4;

  @override
  MigrationStrategy get migration => MigrationStrategy(
        onUpgrade: (Migrator m, int from, int to) async {
          if (from < 2) {
            await m.createTable(quests);
          }
          if (from < 3) {
            await m.addColumn(users, users.exerciseVariants);
          }
          if (from < 4) {
            await m.addColumn(users, users.trainingDays);
            await m.addColumn(users, users.notificationSettings);
          }
        },
      );
}

LazyDatabase _openConnection() {
  return LazyDatabase(() async {
    final dbFolder = await getApplicationDocumentsDirectory();
    final file = File(p.join(dbFolder.path, 'slrpg.sqlite'));
    return NativeDatabase.createInBackground(file);
  });
}
