using CMSMicroservice.Domain.Events;
namespace CMSMicroservice.Application.UserCartsCQ.Commands.CreateNewUserCarts;
public class CreateNewUserCartsCommandHandler : IRequestHandler<CreateNewUserCartsCommand, CreateNewUserCartsResponseDto>
{
    private readonly IApplicationDbContext _context;

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

    public async Task<CreateNewUserCartsResponseDto> Handle(CreateNewUserCartsCommand request,
        CancellationToken cancellationToken)
    {
        var entity = request.Adapt<UserCart>();
        var existingUserCart = await _context.UserCarts
            .FirstOrDefaultAsync(x => x.UserId == entity.UserId && x.ProductId == entity.ProductId && !x.IsDeleted, cancellationToken);
        if (existingUserCart != null)
        {
            existingUserCart.Count += entity.Count;
            _context.UserCarts.Update(existingUserCart);
            existingUserCart.AddDomainEvent(new UpdateUserCartsEvent(existingUserCart));
            await _context.SaveChangesAsync(cancellationToken);
            return existingUserCart.Adapt<CreateNewUserCartsResponseDto>();
        }
        await _context.UserCarts.AddAsync(entity, cancellationToken);
        entity.AddDomainEvent(new CreateNewUserCartsEvent(entity));
        await _context.SaveChangesAsync(cancellationToken);
        return entity.Adapt<CreateNewUserCartsResponseDto>();
    }
}
