using CMSMicroservice.Application.DiscountShopCQ.Queries.GetDiscountCategories;
using CMSMicroservice.Protobuf.Protos.DiscountCategory;
using Mapster;
using AppDiscountCategoryDto = CMSMicroservice.Application.DiscountShopCQ.Queries.GetDiscountCategories.DiscountCategoryDto;
using ProtoDiscountCategoryDto = CMSMicroservice.Protobuf.Protos.DiscountCategory.DiscountCategoryDto;

namespace CMSMicroservice.WebApi.Common.Mappings;

public class DiscountCategoryProfile : IRegister
{
    void IRegister.Register(TypeAdapterConfig config)
    {
        // Map from Application DTO to Proto Response
        config.NewConfig<GetDiscountCategoriesResponseDto, GetDiscountCategoriesResponse>()
            .MapWith(src => MapToResponse(src));

        // Map individual category DTO
        config.NewConfig<AppDiscountCategoryDto, ProtoDiscountCategoryDto>()
            .MapWith(src => MapCategory(src));
    }

    private static GetDiscountCategoriesResponse MapToResponse(GetDiscountCategoriesResponseDto src)
    {
        var response = new GetDiscountCategoriesResponse();
        if (src.Categories != null)
        {
            foreach (var category in src.Categories)
            {
                response.Categories.Add(MapCategory(category));
            }
        }
        return response;
    }

    private static ProtoDiscountCategoryDto MapCategory(AppDiscountCategoryDto src)
    {
        var proto = new ProtoDiscountCategoryDto
        {
            Id = src.Id,
            Name = src.Name ?? string.Empty,
            Title = src.Title ?? string.Empty,
            Description = src.Description,
            ImagePath = src.ImagePath,
            ParentCategoryId = src.ParentCategoryId,
            SortOrder = src.SortOrder,
            IsActive = src.IsActive,
            ProductCount = src.ProductCount
        };

        // Recursively map children
        if (src.Children != null)
        {
            foreach (var child in src.Children)
            {
                proto.Children.Add(MapCategory(child));
            }
        }

        return proto;
    }
}
