using MediatR;
using TakeoutSaaS.Application.App.Products.Commands;
using TakeoutSaaS.Application.App.Products.Dto;
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 BindCategoryProductsCommandHandler(
    IProductRepository productRepository,
    ITenantProvider tenantProvider)
    : IRequestHandler<BindCategoryProductsCommand, ProductCategoryProductBindResultDto>
{
    /// <inheritdoc />
    public async Task<ProductCategoryProductBindResultDto> Handle(BindCategoryProductsCommand request, CancellationToken cancellationToken)
    {
        var tenantId = tenantProvider.GetCurrentTenantId();
        var category = await productRepository.FindCategoryByIdAsync(request.CategoryId, tenantId, cancellationToken);
        if (category is null || category.StoreId != request.StoreId)
        {
            throw new BusinessException(ErrorCodes.NotFound, "分类不存在");
        }

        var distinctProductIds = request.ProductIds
            .Where(id => id > 0)
            .Distinct()
            .ToList();
        if (distinctProductIds.Count == 0)
        {
            return new ProductCategoryProductBindResultDto
            {
                TotalCount = 0,
                SuccessCount = 0,
                FailedCount = 0
            };
        }

        var successCount = await productRepository.BatchUpdateProductCategoryAsync(
            tenantId,
            request.StoreId,
            request.CategoryId,
            distinctProductIds,
            cancellationToken);
        await productRepository.SaveChangesAsync(cancellationToken);

        return new ProductCategoryProductBindResultDto
        {
            TotalCount = distinctProductIds.Count,
            SuccessCount = successCount,
            FailedCount = Math.Max(0, distinctProductIds.Count - successCount)
        };
    }
}
