namespace Adapters.Driven.Persistence.DataLoaders;

using Adapters.Driven.Persistence.Context;
using Domain.Entities;
using GreenDonut;
using Microsoft.EntityFrameworkCore;

public class StudentByIdDataLoader : BatchDataLoader<int, Student>
{
    private readonly IDbContextFactory<AppDbContext> _contextFactory;

    public StudentByIdDataLoader(
        IDbContextFactory<AppDbContext> contextFactory,
        IBatchScheduler batchScheduler,
        DataLoaderOptions? options = null)
        : base(batchScheduler, options ?? new DataLoaderOptions())
    {
        _contextFactory = contextFactory;
    }

    protected override async Task<IReadOnlyDictionary<int, Student>> LoadBatchAsync(
        IReadOnlyList<int> keys,
        CancellationToken ct)
    {
        await using var context = await _contextFactory.CreateDbContextAsync(ct);
        return await context.Students
            .Where(s => keys.Contains(s.Id))
            .ToDictionaryAsync(s => s.Id, ct);
    }
}
