namespace Adapters.Driven.Persistence.DataLoaders;

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

public class SubjectByIdDataLoader : BatchDataLoader<int, Subject>
{
    private readonly IDbContextFactory<AppDbContext> _contextFactory;

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

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