using MediatR;
using TakeoutSaaS.Application.App.Products.Commands;
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 UnbindCategoryProductCommandHandler(
    IProductRepository productRepository,
    ITenantProvider tenantProvider)
    : IRequestHandler<UnbindCategoryProductCommand>
{
    /// <inheritdoc />
    public async Task Handle(UnbindCategoryProductCommand 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 categories = await productRepository.GetCategoriesByStoreAsync(tenantId, request.StoreId, false, cancellationToken);
        var fallbackCategory = categories
            .Where(item => item.Id != request.CategoryId)
            .OrderBy(item => item.SortOrder)
            .ThenBy(item => item.Id)
            .FirstOrDefault();
        if (fallbackCategory is null)
        {
            throw new BusinessException(ErrorCodes.BadRequest, "无可用目标分类");
        }

        var moved = await productRepository.MoveProductToCategoryAsync(
            tenantId,
            request.StoreId,
            request.CategoryId,
            fallbackCategory.Id,
            request.ProductId,
            cancellationToken);
        if (!moved)
        {
            throw new BusinessException(ErrorCodes.NotFound, "商品不存在");
        }

        await productRepository.SaveChangesAsync(cancellationToken);
    }
}
