using CMSMicroservice.Domain.Events;
namespace CMSMicroservice.Application.UserCartsCQ.Commands.DeleteUserCarts;
public class DeleteUserCartsCommandHandler : IRequestHandler<DeleteUserCartsCommand, Unit>
{
    private readonly IApplicationDbContext _context;

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

    public async Task<Unit> Handle(DeleteUserCartsCommand request, CancellationToken cancellationToken)
    {
        var entity = await _context.UserCarts
            .FirstOrDefaultAsync(x => x.Id == request.Id, cancellationToken) ?? throw new NotFoundException(nameof(UserCart), request.Id);
        entity.IsDeleted = true;
        _context.UserCarts.Update(entity);
        entity.AddDomainEvent(new DeleteUserCartsEvent(entity));
        await _context.SaveChangesAsync(cancellationToken);
        return Unit.Value;
    }
}
