import 'package:drift/drift.dart' show Value; import 'package:riverpod_annotation/riverpod_annotation.dart'; import 'package:timetrack/core/database/app_database.dart' as db; import 'package:timetrack/features/entries/data/entries_repository.dart'; import 'package:timetrack/features/entries/data/time_entry_mapper.dart'; import 'package:timetrack/features/entries/domain/time_entry.dart'; part 'drift_entries_repository.g.dart'; class DriftTimeEntriesRepository implements TimeEntriesRepository { DriftTimeEntriesRepository(this._db); final db.AppDatabase _db; @override Stream> watchAll() => _db.timeEntriesDao.watchAll().asyncMap(_enrichWithTags); @override Stream> watchByProject(int projectId) => _db.timeEntriesDao.watchByProject(projectId).asyncMap(_enrichWithTags); @override Stream> watchByDateRange(DateTime from, DateTime to) => _db.timeEntriesDao.watchByDateRange(from, to).asyncMap(_enrichWithTags); @override Future getActiveEntry() async { final row = await _db.timeEntriesDao.getActiveEntry(); if (row == null) return null; final tags = await _db.timeEntriesDao.getTagsForEntry(row.id); return row.toDomain(tags: tags.map((t) => t.name).toList()); } @override Future create(TimeEntry entry) async { final id = await _db.timeEntriesDao.insertEntry(entry.toInsertCompanion()); if (entry.tags.isNotEmpty) { await _db.tagsDao.setTagsForEntry(id, entry.tags); } return id; } @override Future update(TimeEntry entry) async { await _db.timeEntriesDao.updateEntry( entry.toInsertCompanion().copyWith(id: Value(entry.id)), ); await _db.tagsDao.setTagsForEntry(entry.id, entry.tags); } @override Future delete(int id) => _db.timeEntriesDao.deleteEntry(id); Future> _enrichWithTags(List rows) async { final result = []; for (final row in rows) { final tags = await _db.timeEntriesDao.getTagsForEntry(row.id); result.add(row.toDomain(tags: tags.map((t) => t.name).toList())); } return result; } } @riverpod TimeEntriesRepository timeEntriesRepository(TimeEntriesRepositoryRef ref) { final database = ref.watch(db.appDatabaseProvider); return DriftTimeEntriesRepository(database); }