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

namespace CMSMicroservice.Application.BlogPostImageCQ.Queries.GetBlogPostImages;

public class GetBlogPostImagesQueryHandler : IRequestHandler<GetBlogPostImagesQuery, List<BlogPostImageDto>>
{
    private readonly IApplicationDbContext _context;

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

    public async Task<List<BlogPostImageDto>> Handle(GetBlogPostImagesQuery request, CancellationToken cancellationToken)
    {
        var images = await _context.BlogPostImages
            .Where(x => x.BlogPostId == request.BlogPostId && !x.IsDeleted)
            .OrderBy(x => x.SortOrder)
            .Select(x => new BlogPostImageDto
            {
                Id = x.Id,
                BlogPostId = x.BlogPostId,
                ImagePath = x.ImagePath,
                ThumbnailPath = x.ThumbnailPath,
                AltText = x.AltText,
                Caption = x.Caption,
                SortOrder = x.SortOrder
            })
            .ToListAsync(cancellationToken);

        return images;
    }
}
