using CMSMicroservice.Application.Common.Interfaces;
using CMSMicroservice.Domain.Entities;

namespace CMSMicroservice.Application.ProductsCQ.Commands.RemoveProductImage;

public class RemoveProductImageCommandHandler : IRequestHandler<RemoveProductImageCommand, Unit>
{
    private readonly IApplicationDbContext _context;

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

    public async Task<Unit> Handle(RemoveProductImageCommand request, CancellationToken cancellationToken)
    {
        var gallery = await _context.ProductGalleries
            .Include(pg => pg.ProductImage)
            .FirstOrDefaultAsync(pg => pg.Id == request.ProductGalleryId, cancellationToken)
            ?? throw new NotFoundException(nameof(ProductGallery), request.ProductGalleryId);

        // Remove gallery entry
        _context.ProductGalleries.Remove(gallery);

        // Remove the product image if it exists and is not referenced by other galleries
        if (gallery.ProductImage != null)
        {
            var otherReferences = await _context.ProductGalleries
                .AnyAsync(pg => pg.ProductImageId == gallery.ProductImageId && pg.Id != gallery.Id, cancellationToken);
            
            if (!otherReferences)
            {
                _context.ProductImages.Remove(gallery.ProductImage);
            }
        }

        await _context.SaveChangesAsync(cancellationToken);
        return Unit.Value;
    }
}
