using Microsoft.EntityFrameworkCore;
using Netina.Common.Models.Api;
using Netina.Common.Models.Exception;
using Netina.Domain.CommandQueries.Queries;
using Netina.Domain.Dtos.LargDtos;
using Netina.Domain.Entities.Orders;
using Netina.Repository.Repositories.Base.Contracts;

namespace Netina.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;
    }
}