using MediatR;
using TakeoutSaaS.Application.App.Merchants.Commands;
using TakeoutSaaS.Domain.Merchants.Repositories;
using TakeoutSaaS.Shared.Abstractions.Constants;
using TakeoutSaaS.Shared.Abstractions.Exceptions;
using TakeoutSaaS.Shared.Abstractions.Tenancy;

namespace TakeoutSaaS.Application.App.Merchants.Handlers;

/// <summary>
/// 类目排序处理器。
/// </summary>
public sealed class ReorderMerchantCategoriesCommandHandler(
    IMerchantCategoryRepository categoryRepository,
    ITenantProvider tenantProvider)
    : IRequestHandler<ReorderMerchantCategoriesCommand, bool>
{
    /// <summary>
    /// 调整类目排序。
    /// </summary>
    /// <param name="request">排序命令。</param>
    /// <param name="cancellationToken">取消标记。</param>
    /// <returns>执行结果。</returns>
    public async Task<bool> Handle(ReorderMerchantCategoriesCommand request, CancellationToken cancellationToken)
    {
        // 1. 获取租户并查询类目
        var tenantId = tenantProvider.GetCurrentTenantId();
        var categories = await categoryRepository.ListAsync(tenantId, cancellationToken);
        var map = categories.ToDictionary(x => x.Id);

        // 2. 更新排序
        foreach (var item in request.Items)
        {
            if (!map.TryGetValue(item.CategoryId, out var category))
            {
                throw new BusinessException(ErrorCodes.NotFound, $"类目 {item.CategoryId} 不存在");
            }

            category.DisplayOrder = item.DisplayOrder;
        }

        // 3. 持久化
        await categoryRepository.UpdateRangeAsync(map.Values, cancellationToken);
        await categoryRepository.SaveChangesAsync(cancellationToken);
        return true;
    }
}
