using Microsoft.EntityFrameworkCore;

namespace Netina.Repository.Handlers.Products;

public class GetProductQueryHandler : IRequestHandler<GetProductQuery, GetProductResponseDto>
{
    private readonly IRepositoryWrapper _repositoryWrapper;
    private readonly IMediator _mediator;

    public GetProductQueryHandler(IRepositoryWrapper repositoryWrapper,IMediator mediator)
    {
        _repositoryWrapper = repositoryWrapper;
        _mediator = mediator;
    }
    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 AppException("Product not found", ApiResultStatusCode.NotFound);

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

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