using CMSMicroservice.Application.Common.Interfaces;
using MediatR;
using Microsoft.EntityFrameworkCore;

namespace CMSMicroservice.Application.BlogPostImageCQ.Commands.ReorderBlogPostImages;

public class ReorderBlogPostImagesCommandHandler : IRequestHandler<ReorderBlogPostImagesCommand, Unit>
{
    private readonly IApplicationDbContext _context;

    public ReorderBlogPostImagesCommandHandler(IApplicationDbContext context)
    {
        _context = context;
    }

    public async Task<Unit> Handle(ReorderBlogPostImagesCommand request, CancellationToken cancellationToken)
    {
        var ids = request.Items.Select(x => x.Id).ToList();
        var images = await _context.BlogPostImages
            .Where(x => ids.Contains(x.Id) && !x.IsDeleted)
            .ToListAsync(cancellationToken);

        foreach (var item in request.Items)
        {
            var image = images.FirstOrDefault(x => x.Id == item.Id);
            if (image != null)
                image.SortOrder = item.SortOrder;
        }

        await _context.SaveChangesAsync(cancellationToken);

        return Unit.Value;
    }
}
