using Microsoft.EntityFrameworkCore;
using NetinaShop.Domain.Entities.Orders;

namespace NetinaShop.Repository.Handlers.Orders;

public class GetUserOrdersQueryHandler : IRequestHandler<GetUserOrdersQuery, List<OrderSDto>>
{
    private readonly ICurrentUserService _currentUserService;
    private readonly IRepositoryWrapper _repositoryWrapper;

    public GetUserOrdersQueryHandler(ICurrentUserService currentUserService,IRepositoryWrapper repositoryWrapper)
    {
        _currentUserService = currentUserService;
        _repositoryWrapper = repositoryWrapper;
    }
    public async Task<List<OrderSDto>> Handle(GetUserOrdersQuery request, CancellationToken cancellationToken)
    {
        Guid userId = Guid.Empty;
        if (request.UserId == default)
        {
            if (_currentUserService.UserId == null)
                throw new AppException("Token is wrong", ApiResultStatusCode.UnAuthorized);
            if (!Guid.TryParse(_currentUserService.UserId, out userId))
                throw new AppException("Token is wrong", ApiResultStatusCode.UnAuthorized);
        }
        else
            userId = request.UserId;

        var orders = await _repositoryWrapper.SetRepository<Order>()
            .TableNoTracking
            .Where(o => o.UserId == userId)
            .Select(OrderMapper.ProjectToSDto)
            .ToListAsync(cancellationToken);

        return orders;
    }
}