using TakeoutSaaS.Application.App.Products.Dto;
using TakeoutSaaS.Domain.Products.Entities;

namespace TakeoutSaaS.Application.App.Products;

/// <summary>
/// 规格做法模板 DTO 映射工厂。
/// </summary>
internal static class ProductSpecTemplateDtoFactory
{
    /// <summary>
    /// 将模板实体映射为页面 DTO。
    /// </summary>
    public static ProductSpecTemplateItemDto ToDto(
        ProductSpecTemplate template,
        IReadOnlyDictionary<long, List<ProductSpecTemplateOption>> optionsLookup,
        IReadOnlyDictionary<long, List<long>> productIdsLookup)
    {
        var options = optionsLookup.TryGetValue(template.Id, out var optionList)
            ? optionList
            : [];

        var productIds = productIdsLookup.TryGetValue(template.Id, out var ids)
            ? ids
            : [];

        return new ProductSpecTemplateItemDto
        {
            Id = template.Id,
            Name = template.Name,
            Type = ProductSpecTemplateMapping.ToTemplateTypeText(template.TemplateType),
            SelectionType = ProductSpecTemplateMapping.ToSelectionTypeText(template.SelectionType),
            IsRequired = template.IsRequired,
            Sort = template.SortOrder,
            Status = ProductSpecTemplateMapping.ToStatusText(template.IsEnabled),
            ProductCount = productIds.Count,
            ProductIds = productIds,
            Values = options
                .OrderBy(x => x.SortOrder)
                .ThenBy(x => x.Id)
                .Select(option => new ProductSpecTemplateOptionDto
                {
                    Id = option.Id,
                    Name = option.Name,
                    ExtraPrice = option.ExtraPrice,
                    Sort = option.SortOrder
                })
                .ToList(),
            UpdatedAt = template.UpdatedAt ?? template.CreatedAt
        };
    }
}
