namespace Netina.Core.EntityServices.OrderBagHandlers;

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

        var customer = await repositoryWrapper.SetRepository<Customer>()
            .TableNoTracking
            .FirstOrDefaultAsync(c => c.UserId == userId, cancellationToken);
        if (customer == null)
        {
            customer = new Customer
            {
                UserId = userId
            };
            repositoryWrapper.SetRepository<Customer>()
                .Add(customer);
            await repositoryWrapper.SaveChangesAsync(cancellationToken);
        }

        var order = await repositoryWrapper.SetRepository<Order>()
            .TableNoTracking
            .FirstOrDefaultAsync(o => o.CustomerId == customer.Id && 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;
    }
}