using CMSMicroservice.Application.Common.Exceptions;
using CMSMicroservice.Application.Common.Interfaces;
using CMSMicroservice.Domain.Entities.Blog;
using MediatR;
using Microsoft.EntityFrameworkCore;

namespace CMSMicroservice.Application.BlogCategoryCQ.Queries.GetBlogCategory;

public class GetBlogCategoryQueryHandler : IRequestHandler<GetBlogCategoryQuery, BlogCategoryDto>
{
    private readonly IApplicationDbContext _context;

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

    public async Task<BlogCategoryDto> Handle(GetBlogCategoryQuery request, CancellationToken cancellationToken)
    {
        var entity = await _context.BlogCategories
            .Include(x => x.BlogPostCategories)
            .FirstOrDefaultAsync(x => x.Id == request.Id && !x.IsDeleted, cancellationToken);

        if (entity == null)
            throw new NotFoundException(nameof(BlogCategory), request.Id);

        return new BlogCategoryDto
        {
            Id = entity.Id,
            Title = entity.Title,
            Slug = entity.Slug,
            Description = entity.Description,
            IconName = entity.IconName,
            SortOrder = entity.SortOrder,
            IsActive = entity.IsActive,
            PostCount = entity.BlogPostCategories.Count,
            Created = entity.Created,
            LastModified = entity.LastModified
        };
    }
}
