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

namespace CMSMicroservice.Application.DiscountShopCQ.Commands.DeleteDiscountProductImage;

public class DeleteDiscountProductImageCommandHandler : IRequestHandler<DeleteDiscountProductImageCommand, bool>
{
    private readonly IApplicationDbContext _context;

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

    public async Task<bool> Handle(DeleteDiscountProductImageCommand request, CancellationToken cancellationToken)
    {
        var image = await _context.DiscountProductImages
            .FirstOrDefaultAsync(i => i.Id == request.Id, cancellationToken);

        if (image == null)
            return false;

        _context.DiscountProductImages.Remove(image);
        await _context.SaveChangesAsync(cancellationToken);

        // Reorder remaining images for this product
        var remainingImages = await _context.DiscountProductImages
            .Where(i => i.DiscountProductId == image.DiscountProductId)
            .OrderBy(i => i.SortOrder)
            .ToListAsync(cancellationToken);

        for (int i = 0; i < remainingImages.Count; i++)
        {
            remainingImages[i].SortOrder = i + 1;
        }

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