namespace NetinaShop.Core.EntityServices.OrderBagHandlers;

public class GetUserOrderBagQueryHandler : IRequestHandler<GetUserOrderBagQuery,Order>
{
    private readonly IRepositoryWrapper _repositoryWrapper;
    private readonly ICurrentUserService _currentUserService;
    private readonly IMediator _mediator;

    public GetUserOrderBagQueryHandler(IRepositoryWrapper repositoryWrapper,ICurrentUserService currentUserService,IMediator mediator)
    {
        _repositoryWrapper = repositoryWrapper;
        _currentUserService = currentUserService;
        _mediator = mediator;
    }
    public async Task<Order> Handle(GetUserOrderBagQuery request, CancellationToken cancellationToken)
    {
        if (_currentUserService.UserId == null)
            throw new AppException("User id notfound", ApiResultStatusCode.BadRequest);
        if (!Guid.TryParse(_currentUserService.UserId, out Guid userId))
            throw new AppException("User id wrong",ApiResultStatusCode.BadRequest);

        var order = await _repositoryWrapper.SetRepository<Order>()
            .TableNoTracking
            .FirstOrDefaultAsync(o => o.UserId == userId && o.OrderStatus == OrderStatus.OrderBag,cancellationToken);
        
        if (order == null)
            order = await _mediator.Send(new CreateBaseOrderCommand(userId),cancellationToken);
        else
        {
            var orderProducts = await _repositoryWrapper.SetRepository<OrderProduct>()
                .TableNoTracking
                .Where(op=>op.OrderId==order.Id)
                .ToListAsync(cancellationToken);

            orderProducts.ForEach(op=>order.AddOrderProduct(op));
        }

        return order;
    }
}