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

namespace CMSMicroservice.Application.DiscountShopCQ.Commands.ReorderDiscountProductImages;

public class ReorderDiscountProductImagesCommandHandler : IRequestHandler<ReorderDiscountProductImagesCommand, bool>
{
    private readonly IApplicationDbContext _context;

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

    public async Task<bool> Handle(ReorderDiscountProductImagesCommand request, CancellationToken cancellationToken)
    {
        var images = await _context.DiscountProductImages
            .Where(i => i.DiscountProductId == request.DiscountProductId)
            .ToListAsync(cancellationToken);

        if (!images.Any())
            return false;

        // Validate all image IDs belong to this product
        var imageIdSet = images.Select(i => i.Id).ToHashSet();
        if (!request.ImageIds.All(id => imageIdSet.Contains(id)))
            return false;

        // Update sort order based on the new order
        for (int i = 0; i < request.ImageIds.Count; i++)
        {
            var image = images.FirstOrDefault(img => img.Id == request.ImageIds[i]);
            if (image != null)
            {
                image.SortOrder = i + 1;
            }
        }

        await _context.SaveChangesAsync(cancellationToken);
        return true;
    }
}
