using MediatR;
using TakeoutSaaS.Application.App.Products.Commands;
using TakeoutSaaS.Application.App.Products.Dto;
using TakeoutSaaS.Domain.Products.Entities;
using TakeoutSaaS.Domain.Products.Repositories;
using TakeoutSaaS.Shared.Abstractions.Constants;
using TakeoutSaaS.Shared.Abstractions.Exceptions;
using TakeoutSaaS.Shared.Abstractions.Tenancy;

namespace TakeoutSaaS.Application.App.Products.Handlers;

/// <summary>
/// 保存商品标签命令处理器。
/// </summary>
public sealed class SaveProductLabelCommandHandler(
    IProductRepository productRepository,
    ITenantProvider tenantProvider)
    : IRequestHandler<SaveProductLabelCommand, ProductLabelItemDto>
{
    /// <inheritdoc />
    public async Task<ProductLabelItemDto> Handle(SaveProductLabelCommand request, CancellationToken cancellationToken)
    {
        // 1. 归一化并校验输入。
        var tenantId = tenantProvider.GetCurrentTenantId();
        var normalizedName = request.Name.Trim();
        if (string.IsNullOrWhiteSpace(normalizedName))
        {
            throw new BusinessException(ErrorCodes.BadRequest, "标签名称不能为空");
        }

        if (!ProductLabelMapping.TryParseStatus(request.Status, out var isEnabled))
        {
            throw new BusinessException(ErrorCodes.BadRequest, "status 参数不合法");
        }

        if (!ProductLabelMapping.TryNormalizeColor(request.Color, out var normalizedColor))
        {
            throw new BusinessException(ErrorCodes.BadRequest, "标签颜色格式不合法");
        }

        var normalizedSort = Math.Max(0, request.Sort);

        // 2. 校验门店内名称唯一。
        var isDuplicate = await productRepository.ExistsLabelNameAsync(
            tenantId,
            request.StoreId,
            normalizedName,
            request.LabelId,
            cancellationToken);
        if (isDuplicate)
        {
            throw new BusinessException(ErrorCodes.Conflict, "标签名称已存在");
        }

        // 3. 创建或更新标签。
        ProductLabel label;
        if (!request.LabelId.HasValue)
        {
            label = new ProductLabel
            {
                StoreId = request.StoreId,
                Name = normalizedName,
                Color = normalizedColor,
                SortOrder = normalizedSort,
                IsEnabled = isEnabled
            };

            await productRepository.AddLabelAsync(label, cancellationToken);
            await productRepository.SaveChangesAsync(cancellationToken);
        }
        else
        {
            var existing = await productRepository.FindLabelByIdAsync(request.LabelId.Value, tenantId, cancellationToken);
            if (existing is null || existing.StoreId != request.StoreId)
            {
                throw new BusinessException(ErrorCodes.NotFound, "标签不存在");
            }

            existing.Name = normalizedName;
            existing.Color = normalizedColor;
            existing.SortOrder = normalizedSort;
            existing.IsEnabled = isEnabled;
            label = existing;

            await productRepository.UpdateLabelAsync(label, cancellationToken);
            await productRepository.SaveChangesAsync(cancellationToken);
        }

        // 4. 回读关联数量并返回快照。
        var productCounts = await productRepository.CountLabelProductsByLabelIdsAsync(
            tenantId,
            request.StoreId,
            [label.Id],
            cancellationToken);
        return ProductLabelDtoFactory.ToDto(label, productCounts);
    }
}
