using Core.Models;
using Core.Services;
namespace WebApp.Services;
///
/// Creates or updates #Student:{id} notes when imported fields actually change.
///
public class StudentNotesImportSaveService : IStudentNotesImportSaveService
{
private readonly INotesService _notesService;
private readonly INoteNamingService _noteNamingService;
private readonly ILogger _logger;
public StudentNotesImportSaveService(
INotesService notesService,
INoteNamingService noteNamingService,
ILogger logger)
{
_notesService = notesService;
_noteNamingService = noteNamingService;
_logger = logger;
}
///
public async Task SaveAsync(
StudentNotesImportResult parseResult,
CancellationToken cancellationToken = default)
{
var result = new StudentNotesImportSaveResult();
var existingNotes = await _notesService.GetStudentNotesAsync(
parseResult.Matches.Select(m => m.Student.Id));
var actions = StudentNotesImportPlan.Create(parseResult, existingNotes.Keys.ToHashSet());
result.StudentsUnchanged = parseResult.Matches.Count - actions.Count;
foreach (var action in actions)
{
cancellationToken.ThrowIfCancellationRequested();
if (action.Kind == StudentNotePersistKind.Update
&& existingNotes.TryGetValue(action.StudentId, out var existing))
{
existing.Content = action.Markdown;
await _notesService.UpdateNoteAsync(existing);
result.NotesUpdated++;
continue;
}
await _notesService.CreateNoteAsync(new Core.Entities.Note
{
Title = _noteNamingService.GetStudentNoteTitle(action.StudentId),
Content = action.Markdown
});
result.NotesCreated++;
}
_logger.LogInformation(
"Student notes import saved. Created={Created}, Updated={Updated}, Unchanged={Unchanged}",
result.NotesCreated,
result.NotesUpdated,
result.StudentsUnchanged);
return result;
}
}