using CMSMicroservice.Application.Common.Interfaces;
using MediatR;
using Microsoft.EntityFrameworkCore;

namespace CMSMicroservice.Application.DiscountShopCQ.Queries.GetDiscountProductImages;

public class GetDiscountProductImagesQueryHandler : IRequestHandler<GetDiscountProductImagesQuery, List<DiscountProductImageDto>>
{
    private readonly IApplicationDbContext _context;

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

    public async Task<List<DiscountProductImageDto>> Handle(GetDiscountProductImagesQuery request, CancellationToken cancellationToken)
    {
        var query = _context.DiscountProductImages
            .Where(i => i.DiscountProductId == request.DiscountProductId);

        if (request.OnlyActive)
            query = query.Where(i => i.IsActive);

        return await query
            .OrderBy(i => i.SortOrder)
            .Select(i => new DiscountProductImageDto
            {
                Id = i.Id,
                DiscountProductId = i.DiscountProductId,
                ImagePath = i.ImagePath,
                ThumbnailPath = i.ThumbnailPath,
                Title = i.Title,
                AltText = i.AltText,
                SortOrder = i.SortOrder,
                IsActive = i.IsActive
            })
            .ToListAsync(cancellationToken);
    }
}
