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 SaveProductCategoryCommandHandler(
    IProductRepository productRepository,
    ITenantProvider tenantProvider)
    : IRequestHandler<SaveProductCategoryCommand, ProductCategoryManageItemDto>
{
    /// <inheritdoc />
    public async Task<ProductCategoryManageItemDto> Handle(SaveProductCategoryCommand request, CancellationToken cancellationToken)
    {
        var tenantId = tenantProvider.GetCurrentTenantId();
        var normalizedName = request.Name.Trim();
        var isDuplicate = await productRepository.ExistsCategoryNameAsync(
            tenantId,
            request.StoreId,
            normalizedName,
            request.CategoryId,
            cancellationToken);
        if (isDuplicate)
        {
            throw new BusinessException(ErrorCodes.Conflict, "分类名称已存在");
        }

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

        var normalizedChannels = ProductCategoryManageMapping.NormalizeChannels(request.Channels);
        if (normalizedChannels.Count == 0)
        {
            throw new BusinessException(ErrorCodes.BadRequest, "请至少选择一个销售渠道");
        }

        ProductCategory category;
        if (request.CategoryId.HasValue)
        {
            var existing = await productRepository.FindCategoryByIdAsync(request.CategoryId.Value, tenantId, cancellationToken);
            if (existing is null || existing.StoreId != request.StoreId)
            {
                throw new BusinessException(ErrorCodes.NotFound, "分类不存在");
            }

            category = existing;
            category.Name = normalizedName;
            category.Description = request.Description.Trim();
            category.Icon = request.Icon.Trim();
            category.SortOrder = Math.Max(1, request.Sort);
            category.IsEnabled = isEnabled;
            category.ChannelsJson = ProductCategoryManageMapping.SerializeChannels(normalizedChannels);
            await productRepository.UpdateCategoryAsync(category, cancellationToken);
        }
        else
        {
            category = new ProductCategory
            {
                StoreId = request.StoreId,
                Name = normalizedName,
                Description = request.Description.Trim(),
                Icon = request.Icon.Trim(),
                SortOrder = Math.Max(1, request.Sort),
                IsEnabled = isEnabled,
                ChannelsJson = ProductCategoryManageMapping.SerializeChannels(normalizedChannels)
            };
            await productRepository.AddCategoryAsync(category, cancellationToken);
        }

        await productRepository.SaveChangesAsync(cancellationToken);

        var productCounts = await productRepository.CountProductsByCategoryIdsAsync(
            tenantId,
            request.StoreId,
            [category.Id],
            cancellationToken);

        return new ProductCategoryManageItemDto
        {
            Id = category.Id,
            Name = category.Name,
            ProductCount = productCounts.GetValueOrDefault(category.Id),
            Sort = category.SortOrder,
            Description = category.Description ?? string.Empty,
            Icon = category.Icon ?? string.Empty,
            Status = ProductCategoryManageMapping.ToStatusText(category.IsEnabled),
            Channels = ProductCategoryManageMapping.DeserializeChannels(category.ChannelsJson)
        };
    }
}
