using CMSMicroservice.Application.BlogPostCQ.Queries.GetBlogPost;
using CMSMicroservice.Application.Common.Interfaces;
using CMSMicroservice.Domain.Enums;
using MediatR;
using Microsoft.EntityFrameworkCore;

namespace CMSMicroservice.Application.BlogPostCQ.Queries.GetFeaturedBlogPosts;

public class GetFeaturedBlogPostsQuery : IRequest<List<GetAllBlogPosts.BlogPostListItemDto>>
{
    public int Count { get; set; } = 5;
}

public class GetFeaturedBlogPostsQueryHandler : IRequestHandler<GetFeaturedBlogPostsQuery, List<GetAllBlogPosts.BlogPostListItemDto>>
{
    private readonly IApplicationDbContext _context;

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

    public async Task<List<GetAllBlogPosts.BlogPostListItemDto>> Handle(GetFeaturedBlogPostsQuery request, CancellationToken cancellationToken)
    {
        var posts = await _context.BlogPosts
            .Include(x => x.BlogPostCategories).ThenInclude(x => x.BlogCategory)
            .Where(x => !x.IsDeleted && x.Status == BlogPostStatus.Published && x.IsFeatured)
            .OrderBy(x => x.SortOrder)
            .ThenByDescending(x => x.PublishedAt)
            .Take(request.Count)
            .Select(x => new GetAllBlogPosts.BlogPostListItemDto
            {
                Id = x.Id,
                Title = x.Title,
                Slug = x.Slug,
                Summary = x.Summary,
                FeaturedImageThumbnailPath = x.FeaturedImageThumbnailPath,
                Status = (int)x.Status,
                StatusName = GetBlogPostQueryHandler.GetStatusName(x.Status),
                PublishedAt = x.PublishedAt,
                ViewCount = x.ViewCount,
                IsFeatured = x.IsFeatured,
                Created = x.Created,
                Categories = x.BlogPostCategories.Select(c => new BlogPostCategoryDto
                {
                    Id = c.BlogCategory.Id,
                    Title = c.BlogCategory.Title,
                    Slug = c.BlogCategory.Slug
                }).ToList()
            })
            .ToListAsync(cancellationToken);

        return posts;
    }
}
