namespace Eis.Infrastructure.Administration;

internal sealed class AdminResultStatisticsBackfillService(
    AdminOperationalSnapshotLoader operationalSnapshotLoader,
    AdminWorkflowResultSnapshotLoader resultSnapshotLoader,
    AdminResultRepository repository)
{
    public async Task EnsureAsync(CancellationToken cancellationToken)
    {
        if (!await repository.NeedsStatisticsBackfillAsync(cancellationToken)) return;
        var operational = await operationalSnapshotLoader.LoadAsync(cancellationToken);
        var calculations = new List<AdminResultCalculation>();
        foreach (var exam in operational.Exams)
        {
            var registrations = operational.Registrations
                .Where(item => item.ExamId == exam.Id && item.Status == "approved")
                .ToArray();
            if (registrations.Length == 0) continue;
            var results = await resultSnapshotLoader.LoadForExamAsync(exam.Id, cancellationToken);
            calculations.Add(AdminResultStatistics.Calculate(
                exam,
                registrations,
                results,
                DateTimeOffset.UtcNow.ToString("yyyy-MM-dd'T'HH:mm:ss.fff'Z'")));
        }
        if (calculations.Count > 0)
            await repository.ReplaceStatisticsAsync(calculations, cancellationToken);
    }
}
