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

namespace NetinaShop.Repository.Handlers.Orders;

public class GetOrderLDtoQueryHandler: IRequestHandler<GetOrderLDtoQuery,OrderLDto>
{
    private readonly IRepositoryWrapper _repositoryWrapper;

    public GetOrderLDtoQueryHandler(IRepositoryWrapper repositoryWrapper)
    {
        _repositoryWrapper = repositoryWrapper;
    }
    public async Task<OrderLDto> Handle(GetOrderLDtoQuery request, CancellationToken cancellationToken)
    {
        if (request.Id == default)
            throw new AppException("Order id is null");
        var order = await _repositoryWrapper.SetRepository<Order>()
            .TableNoTracking
            .Where(o => o.Id == request.Id)
            .Select(OrderMapper.ProjectToLDto)
            .FirstOrDefaultAsync(cancellationToken);
        if (order == null)
            throw new AppException("Order not found", ApiResultStatusCode.NotFound);
        return order;
    }
}