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

namespace CMSMicroservice.Application.SitePageCQ.Commands.ReorderSitePageSections;

public class ReorderSitePageSectionsCommandHandler : IRequestHandler<ReorderSitePageSectionsCommand, Unit>
{
    private readonly IApplicationDbContext _context;

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

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

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

        await _context.SaveChangesAsync(cancellationToken);

        return Unit.Value;
    }
}
