namespace CMSMicroservice.Application.ProductsCQ.Queries.GetProducts;
public class GetProductsQueryHandler : IRequestHandler<GetProductsQuery, GetProductsResponseDto>
{
    private readonly IApplicationDbContext _context;

    public GetProductsQueryHandler(IApplicationDbContext context)
    {
        _context = context;
    }

    public async Task<GetProductsResponseDto> Handle(GetProductsQuery request,
        CancellationToken cancellationToken)
    {
        var response = await _context.Products
            .AsNoTracking()
            .Where(x => x.Id == request.Id)
            .Select(x => new GetProductsResponseDto
            {
                Id = x.Id,
                Title = x.Title,
                Description = x.Description,
                ShortInfomation = x.ShortInfomation,
                FullInformation = x.FullInformation,
                Price = x.Price,
                Discount = x.Discount,
                Rate = x.Rate,
                ImagePath = x.ImagePath,
                ThumbnailPath = x.ThumbnailPath,
                SaleCount = x.SaleCount,
                ViewCount = x.ViewCount,
                RemainingCount = x.RemainingCount,
                CategoryIds = x.ProductCategories
                    .Select(pc => pc.CategoryId)
                    .ToList()
            })
            .FirstOrDefaultAsync(cancellationToken);

        return response ?? throw new NotFoundException(nameof(Product), request.Id);
    }
}
