using LiteCqrs;
using Microsoft.EntityFrameworkCore;
using TeleWave.Application.Common.Interfaces;
using TeleWave.Application.Common.Models;

namespace TeleWave.Application.Library.Collections.FillCollectionPosters;

public sealed class FillCollectionPostersCommandHandler(
    IAppDbContext dbContext,
    CollectionPosterPicker picker
) : ICommandHandler<FillCollectionPostersCommand, Result<int>>
{
    public async Task<Result<int>> Handle(
        FillCollectionPostersCommand command,
        CancellationToken cancellationToken
    )
    {
        var query = dbContext.Collections.Include(c => c.Items).AsQueryable();

        if (command.CollectionIds is { Count: > 0 } ids)
            query = query.Where(c => ids.Contains(c.Id));

        var collections = await query.ToListAsync(cancellationToken);
        var filled = await picker.FillAsync(collections, cancellationToken);

        return Result.Success(filled);
    }
}
