using CMSMicroservice.Application.Common.Interfaces;

namespace CMSMicroservice.Application.ProductsCQ.Queries.GetProductGallery;

public class GetProductGalleryQueryHandler : IRequestHandler<GetProductGalleryQuery, GetProductGalleryResponseDto>
{
    private readonly IApplicationDbContext _context;

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

    public async Task<GetProductGalleryResponseDto> Handle(GetProductGalleryQuery request, CancellationToken cancellationToken)
    {
        var galleries = await _context.ProductGalleries
            .AsNoTracking()
            .Where(pg => pg.ProductId == request.ProductId)
            .Include(pg => pg.ProductImage)
            .ToListAsync(cancellationToken);

        return new GetProductGalleryResponseDto
        {
            Items = galleries.Select(pg => new ProductGalleryItemDto
            {
                ProductGalleryId = pg.Id,
                ProductImageId = pg.ProductImageId,
                Title = pg.ProductImage?.Title ?? string.Empty,
                ImagePath = pg.ProductImage?.ImagePath ?? string.Empty,
                ImageThumbnailPath = pg.ProductImage?.ImageThumbnailPath ?? string.Empty
            }).ToList()
        };
    }
}
