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

namespace CMSMicroservice.Application.BlogPostCQ.Queries.GetPublishedBlogPosts;

public class GetPublishedBlogPostsQuery : IRequest<GetAllBlogPosts.GetAllBlogPostsResponseDto>
{
    public int PageNumber { get; set; } = 1;
    public int PageSize { get; set; } = 10;
    public string? SearchTerm { get; set; }
    public long? CategoryId { get; set; }
}

public class GetPublishedBlogPostsQueryHandler : IRequestHandler<GetPublishedBlogPostsQuery, GetAllBlogPosts.GetAllBlogPostsResponseDto>
{
    private readonly IApplicationDbContext _context;

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

    public async Task<GetAllBlogPosts.GetAllBlogPostsResponseDto> Handle(GetPublishedBlogPostsQuery request, CancellationToken cancellationToken)
    {
        var query = _context.BlogPosts
            .Include(x => x.BlogPostCategories).ThenInclude(x => x.BlogCategory)
            .Where(x => !x.IsDeleted && x.Status == BlogPostStatus.Published);

        if (request.CategoryId.HasValue)
            query = query.Where(x => x.BlogPostCategories.Any(c => c.BlogCategoryId == request.CategoryId.Value));
        if (!string.IsNullOrEmpty(request.SearchTerm))
        {
            var term = request.SearchTerm.ToLower();
            query = query.Where(x => x.Title.ToLower().Contains(term) || (x.Summary != null && x.Summary.ToLower().Contains(term)));
        }

        var totalCount = await query.CountAsync(cancellationToken);

        var posts = await query
            .OrderByDescending(x => x.PublishedAt)
            .Skip((request.PageNumber - 1) * request.PageSize)
            .Take(request.PageSize)
            .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);

        var metaData = new MetaData
        {
            TotalCount = totalCount,
            PageSize = request.PageSize,
            CurrentPage = request.PageNumber,
            TotalPage = (int)Math.Ceiling(totalCount / (double)request.PageSize),
            HasNext = request.PageNumber < (int)Math.Ceiling(totalCount / (double)request.PageSize),
            HasPrevious = request.PageNumber > 1
        };

        return new GetAllBlogPosts.GetAllBlogPostsResponseDto { MetaData = metaData, Models = posts };
    }
}
