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

namespace CMSMicroservice.Application.DiscountShopCQ.Commands.ClearCart;

public class ClearCartCommandHandler : IRequestHandler<ClearCartCommand, bool>
{
    private readonly IApplicationDbContext _context;

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

    public async Task<bool> Handle(ClearCartCommand request, CancellationToken cancellationToken)
    {
        var cartItems = await _context.DiscountShoppingCarts
            .Where(c => c.UserId == request.UserId)
            .ToListAsync(cancellationToken);

        if (!cartItems.Any())
        {
            return true; // Cart already empty
        }

        _context.DiscountShoppingCarts.RemoveRange(cartItems);
        await _context.SaveChangesAsync(cancellationToken);

        return true;
    }
}
