namespace Netina.Repository.Handlers.Products;

public class GetProductQueryHandler(IRepositoryWrapper repositoryWrapper, IMediator mediator)
    : IRequestHandler<GetProductQuery, GetProductResponseDto>
{
    public async Task<GetProductResponseDto> Handle(GetProductQuery request, CancellationToken cancellationToken)
    {
        var ent = await repositoryWrapper.SetRepository<Product>().TableNoTracking
            .Where(b => b.Id == request.Id)
            .Select(ProductMapper.ProjectToLDto)
            .FirstOrDefaultAsync(cancellationToken);

        if (ent == null)
            throw new BaseApiException(ApiResultStatusCode.NotFound,"Product not found");

        await mediator.Send(new CalculateProductDiscountCommand(ent), cancellationToken);

        var response = new GetProductResponseDto
        {
            Product = ent
        };
        return response;
    }
}