using CMSMicroservice.Application.BlogCategoryCQ.Queries.GetBlogCategory;
using CMSMicroservice.Application.Common.Interfaces;
using MediatR;
using Microsoft.EntityFrameworkCore;

namespace CMSMicroservice.Application.BlogCategoryCQ.Queries.GetActiveBlogCategories;

public class GetActiveBlogCategoriesQuery : IRequest<List<BlogCategoryDto>>
{
}

public class GetActiveBlogCategoriesQueryHandler : IRequestHandler<GetActiveBlogCategoriesQuery, List<BlogCategoryDto>>
{
    private readonly IApplicationDbContext _context;

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

    public async Task<List<BlogCategoryDto>> Handle(GetActiveBlogCategoriesQuery request, CancellationToken cancellationToken)
    {
        var categories = await _context.BlogCategories
            .Include(x => x.BlogPostCategories)
            .Where(x => !x.IsDeleted && x.IsActive)
            .OrderBy(x => x.SortOrder)
            .ThenBy(x => x.Title)
            .Select(x => new BlogCategoryDto
            {
                Id = x.Id,
                Title = x.Title,
                Slug = x.Slug,
                Description = x.Description,
                IconName = x.IconName,
                SortOrder = x.SortOrder,
                IsActive = x.IsActive,
                PostCount = x.BlogPostCategories.Count,
                Created = x.Created,
                LastModified = x.LastModified
            })
            .ToListAsync(cancellationToken);

        return categories;
    }
}
