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

namespace CMSMicroservice.Application.DiscountShopCQ.Commands.RemoveFromCart;

public class RemoveFromCartCommandHandler : IRequestHandler<RemoveFromCartCommand, RemoveFromCartResponseDto>
{
    private readonly IApplicationDbContext _context;

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

    public async Task<RemoveFromCartResponseDto> Handle(RemoveFromCartCommand request, CancellationToken cancellationToken)
    {
        var cartItem = await _context.DiscountShoppingCarts
            .FirstOrDefaultAsync(c => c.UserId == request.UserId && c.ProductId == request.ProductId, cancellationToken);

        if (cartItem == null)
        {
            return new RemoveFromCartResponseDto
            {
                Success = false,
                Message = "محصول در سبد خرید یافت نشد"
            };
        }

        _context.DiscountShoppingCarts.Remove(cartItem);
        await _context.SaveChangesAsync(cancellationToken);

        return new RemoveFromCartResponseDto
        {
            Success = true,
            Message = "محصول از سبد خرید حذف شد"
        };
    }
}
