import 'package:mnemo_cards_backend/cron/task.dart' as cron_task; import 'package:mnemo_cards_backend/database/database.dart'; import 'package:mnemo_cards_backend/tests/test_manager.dart'; import 'package:mnemo_cards_common_backend/mnemo_cards_common_backend.dart'; class TestGeneratorTask with cron_task.Task { final TestManager _testManager; final AppDatabase _db; TestGeneratorTask(this._testManager, this._db); @override String get name => 'test_gen'; @override Future task() async { print('Refreshing custom test data...'); try { await _testManager.refreshCustomCreationTestsData(); } catch (e) { print(e); } print('Refreshed custom test data'); final packs = await _db.packDao.getAllPacks(); print('Will generate tests for ${packs.length} packs'); int ok = 0; for (final pack in packs) { try { // Convert CardPack to CardPackModel for updateGeneratedTests final packModel = CardPackModel( id: pack.id, title: pack.title, subtitle: pack.subtitle, description: pack.description, color: pack.color, cover: pack.cover, size: pack.size, version: pack.version, order: pack.order, enabled: pack.enabled, cardsOrder: pack.cardsOrder, googlePlayId: pack.googlePlayId, rustoreId: pack.rustoreId, appStoreId: pack.appStoreId, price: pack.price, currency: pack.currency, ); await _testManager.updateGeneratedTests(packModel); ok++; } catch (e) { print(e); } } print('Generated tests for $ok packs'); print('Purging old generated tests (hard delete TTL)...'); try { final orphanDeleted = await _db.testDao.hardDeleteOrphanGeneratedTests( olderThan: const Duration(hours: 1), ); print('purged $orphanDeleted orphan generated tests'); final deleted = await _db.testDao.hardDeleteOldSoftDeletedGeneratedTests( olderThan: const Duration(days: 7), ); print('purged $deleted old generated tests'); } catch (e) { print('failed to purge old generated tests: $e'); } print('Deleting old test stats'); // Delete test statistics where test doesn't exist (test was deleted) final allTests = await _db.testDao.getAllTests(); final testIds = allTests.map((t) => t.id).toSet(); if (testIds.isEmpty) { // If no tests exist, delete all statistics final count = await (_db.delete(_db.testStatistics)).go(); print('deleted $count old test stats'); return; } // Get all statistics and filter in memory (more efficient for small datasets) final allStats = await (_db.select(_db.testStatistics)).get(); final statsToDelete = allStats.where((stat) => !testIds.contains(stat.testId)).toList(); int count = 0; for (final stat in statsToDelete) { await (_db.delete(_db.testStatistics)..where((ts) => ts.id.equals(stat.id))).go(); count++; } print('deleted $count old test stats'); } @override int get intervalSeconds => 60 * 30; }