// EN: Handler for GetCategoriesQuery.
// VI: Handler cho GetCategoriesQuery.

using MediatR;
using Microsoft.EntityFrameworkCore;
using CatalogService.API.Application.DTOs;
using CatalogService.Infrastructure;

namespace CatalogService.API.Application.Queries;

/// <summary>
/// EN: Handler for querying categories with hierarchical support.
/// VI: Handler query danh mục có hỗ trợ phân cấp.
/// </summary>
public class GetCategoriesQueryHandler : IRequestHandler<GetCategoriesQuery, List<CategoryDto>>
{
    private readonly CatalogContext _context;

    public GetCategoriesQueryHandler(CatalogContext context)
    {
        _context = context ?? throw new ArgumentNullException(nameof(context));
    }

    public async Task<List<CategoryDto>> Handle(GetCategoriesQuery request, CancellationToken cancellationToken)
    {
        var query = _context.Categories
            .Where(c => c.ShopId == request.ShopId);

        // EN: Filter by parent ID if specified
        // VI: Lọc theo ID cha nếu được chỉ định
        if (request.ParentId.HasValue)
        {
            query = query.Where(c => c.ParentId == request.ParentId.Value);
        }
        else
        {
            // EN: Return only root categories if no parent specified
            // VI: Trả về chỉ danh mục gốc nếu không chỉ định cha
            query = query.Where(c => c.ParentId == null);
        }

        var categories = await query
            .OrderBy(c => c.DisplayOrder)
            .ThenBy(c => c.Name)
            .Select(c => new CategoryDto
            {
                Id = c.Id,
                ShopId = c.ShopId,
                Name = c.Name,
                Description = c.Description,
                ParentId = c.ParentId,
                DisplayOrder = c.DisplayOrder,
                IsActive = c.IsActive,
                CreatedAt = c.CreatedAt,
                UpdatedAt = c.UpdatedAt
            })
            .ToListAsync(cancellationToken);

        return categories;
    }
}
