using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using CMSMicroservice.Protobuf.Protos.Category;

namespace FrontOffice.Main.Utilities;

public sealed record CategoryItem(long Id, string Title, long? ParentId, string? ImagePath, bool IsActive);

public class CategoryService
{
    private readonly CMSMicroservice.Protobuf.Protos.Category.CategoryContract.CategoryContractClient _client;
    private List<CategoryItem>? _cache;

    public CategoryService(CMSMicroservice.Protobuf.Protos.Category.CategoryContract.CategoryContractClient client)
    {
        _client = client;
    }

    public async Task<List<CategoryItem>> GetAllAsync(bool forceReload = false)
    {
        if (!forceReload && _cache is { Count: > 0 })
        {
            return _cache;
        }

        var response = await _client.GetAllCategoriesForCustomerAsync(new GetAllCategoriesForCustomerRequest());
        _cache = response.Models
            .Select(dto => new CategoryItem(
                Id: dto.Id,
                Title: dto.Title ?? dto.Name ?? string.Empty,
                ParentId: dto.ParentId,
                ImagePath: dto.ImagePath,
                IsActive: dto.IsActive))
            .ToList();

        return _cache;
    }

    public async Task<CategoryItem?> GetByIdAsync(long id)
    {
        var categories = await GetAllAsync();
        return categories.FirstOrDefault(c => c.Id == id);
    }
}
