namespace FrontOffice.Main.Utilities;

/// <summary>
/// Service for fetching active blog categories (customer-facing).
/// </summary>
public class BlogCategoryService
{
    private readonly CMSMicroservice.Protobuf.Protos.BlogCategory.BlogCategoryContract.BlogCategoryContractClient _client;

    public BlogCategoryService(CMSMicroservice.Protobuf.Protos.BlogCategory.BlogCategoryContract.BlogCategoryContractClient client)
    {
        _client = client;
    }

    /// <summary>
    /// Get all active blog categories (for blog sidebar / filter).
    /// </summary>
    public async Task<List<BlogCategoryDto>> GetActiveCategoriesAsync()
    {
        try
        {
            var response = await _client.GetActiveBlogCategoriesAsync(
                new CMSMicroservice.Protobuf.Protos.BlogCategory.GetActiveBlogCategoriesRequest());

            if (response?.Categories == null || response.Categories.Count == 0)
                return new();

            return response.Categories
                .OrderBy(c => c.SortOrder)
                .Select(c => new BlogCategoryDto
                {
                    Id = c.Id,
                    Title = c.Title,
                    Slug = c.Slug,
                    Description = c.Description,
                    IconName = c.IconName,
                    PostCount = c.PostCount
                })
                .ToList();
        }
        catch (Exception ex)
        {
#if DEBUG
            Console.WriteLine($"BlogCategoryService.GetActiveCategoriesAsync error: {ex.Message}");
#endif
            return new();
        }
    }
}

// ── DTO ──
public class BlogCategoryDto
{
    public long Id { get; set; }
    public string Title { get; set; } = string.Empty;
    public string Slug { get; set; } = string.Empty;
    public string? Description { get; set; }
    public string? IconName { get; set; }
    public int PostCount { get; set; }
}
