import 'package:notas/data/app_database.dart'; import 'package:notas/models/note.dart'; class NoteRepository { NoteRepository({required AppDatabase database}) : _database = database; final AppDatabase _database; Future> loadNotes() async { return _loadNotesFromDatabase(); } Future createNote(Note note) async { final int id = await _database.insertNoteAtTop( NotesCompanion.insert( title: note.title, body: note.body, createdAt: note.createdAt, updatedAt: note.updatedAt, sortIndex: 0, ), ); return note.copyWith(id: id, index: 0); } Future updateNote(Note note) async { final int noteId = note.id ?? (throw ArgumentError('Note id is required to update a note.')); await _database.updateNoteRow( DbNote( id: noteId, title: note.title, body: note.body, createdAt: note.createdAt, updatedAt: note.updatedAt, sortIndex: note.index, ), ); return note; } Future deleteNote(Note note) async { final int noteId = note.id ?? (throw ArgumentError('Note id is required to delete a note.')); await _database.deleteNoteAndShift( id: noteId, removedIndex: note.index, ); } Future moveNote(Note note, int newIndex) async { final int noteId = note.id ?? (throw ArgumentError('Note id is required to reorder a note.')); await _database.moveNote( id: noteId, oldIndex: note.index, newIndex: newIndex, ); } Future> _loadNotesFromDatabase() async { final List rows = await _database.getAllNotes(); return rows.map(_fromRow).toList(); } Note _fromRow(DbNote row) { return Note( id: row.id, title: row.title, body: row.body, createdAt: row.createdAt, updatedAt: row.updatedAt, index: row.sortIndex, ); } }