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

namespace TakeoutSaaS.Application.App.Products;

/// <summary>
/// 加料模板 DTO 映射工厂。
/// </summary>
internal static class ProductAddonTemplateDtoFactory
{
    /// <summary>
    /// 将模板实体映射为页面 DTO。
    /// </summary>
    public static ProductAddonTemplateItemDto 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 ProductAddonTemplateItemDto
        {
            Id = template.Id,
            Name = template.Name,
            Description = template.Description,
            Required = template.IsRequired,
            MinSelect = template.MinSelect,
            MaxSelect = template.MaxSelect,
            Sort = template.SortOrder,
            Status = ProductAddonTemplateMapping.ToStatusText(template.IsEnabled),
            ProductCount = productIds.Count,
            ProductIds = productIds,
            Items = options
                .OrderBy(x => x.SortOrder)
                .ThenBy(x => x.Id)
                .Select(option => new ProductAddonTemplateOptionDto
                {
                    Id = option.Id,
                    Name = option.Name,
                    Price = option.ExtraPrice,
                    Stock = option.Stock,
                    Sort = option.SortOrder,
                    Status = ProductAddonTemplateMapping.ToStatusText(option.IsEnabled)
                })
                .ToList(),
            UpdatedAt = template.UpdatedAt ?? template.CreatedAt
        };
    }
}
