import 'package:drift/drift.dart';
import 'package:flutter/foundation.dart';
import 'package:injectable/injectable.dart';
import 'package:remever/database/dao/collections_dao.dart';
import 'package:remever/database/tables.dart';
import 'connection/connection.dart' as impl;
import 'package:uuid/uuid.dart';

part 'database.g.dart';

@DriftDatabase(
  include: <String>{'sql.drift'},
  daos: <Type>[CollectionsDao],
  tables: <Type>[Collections],
)
@Singleton()
final class AppDatabase extends _$AppDatabase {
  AppDatabase() : super(impl.connect());

  AppDatabase.fromExcecutor(super.executor);

  @override
  int get schemaVersion => 1;

  @override
  MigrationStrategy get migration {
    return MigrationStrategy(
      beforeOpen: (OpeningDetails details) async {
        await enableFK();
        // await customStatement('PRAGMA journal_mode = WAL');
      },
      onCreate: (Migrator migrator) async {
        await migrator.createAll();
      },
      onUpgrade: _onUpgrade,
    );
  }

  Future<void> enableFK() => customStatement('PRAGMA foreign_keys = ON');
  Future<void> disableFK() => customStatement('PRAGMA foreign_keys = OFF');

  // ignore: long-method
  Future<void> _onUpgrade(Migrator m, int from, int to) async {
    await customStatement('PRAGMA foreign_keys = OFF');

    for (int step = from + 1; step <= to; step++) {
      switch (step) {}
    }

    // Assert that the schema is valid after migrations
    if (kDebugMode) {
      final List<QueryRow> wrongForeignKeys =
          await customSelect('PRAGMA foreign_key_check').get();

      assert(
        wrongForeignKeys.isEmpty,
        '${wrongForeignKeys.map((QueryRow e) => e.data)}',
      );
    }
  }

  // --
}
