using ErsatzTV.Core.Api.Filler;
using ErsatzTV.Core.Domain.Filler;
using ErsatzTV.Infrastructure.Data;
using Microsoft.EntityFrameworkCore;
using static ErsatzTV.Application.Filler.Mapper;

namespace ErsatzTV.Application.Filler;

public class GetAllFillerPresetsForApiHandler(IDbContextFactory<TvContext> dbContextFactory)
    : IRequestHandler<GetAllFillerPresetsForApi, List<FillerPresetResponseModel>>
{
    public async Task<List<FillerPresetResponseModel>> Handle(
        GetAllFillerPresetsForApi request,
        CancellationToken cancellationToken)
    {
        await using TvContext dbContext = await dbContextFactory.CreateDbContextAsync(cancellationToken);
        IQueryable<FillerPreset> query = dbContext.FillerPresets.AsNoTracking();
        if (request.FillerKind is { } fillerKind)
        {
            query = query.Where(fp => fp.FillerKind == fillerKind);
        }

        List<FillerPreset> fillerPresets = await query.ToListAsync(cancellationToken);
        return fillerPresets.Map(ProjectToResponseModel).ToList();
    }
}
