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 DeleteProductCategoryCommandHandler(
    IProductRepository productRepository,
    ITenantProvider tenantProvider)
    : IRequestHandler<DeleteProductCategoryCommand>
{
    /// <inheritdoc />
    public async Task Handle(DeleteProductCategoryCommand request, CancellationToken cancellationToken)
    {
        var tenantId = tenantProvider.GetCurrentTenantId();
        var category = await productRepository.FindCategoryByIdAsync(request.CategoryId, tenantId, cancellationToken);
        if (category is null || category.StoreId != request.StoreId)
        {
            return;
        }

        var categoryCounts = await productRepository.CountProductsByCategoryIdsAsync(
            tenantId,
            request.StoreId,
            [request.CategoryId],
            cancellationToken);
        if (categoryCounts.GetValueOrDefault(request.CategoryId) > 0)
        {
            throw new BusinessException(ErrorCodes.BadRequest, "分类下仍有商品，不能删除");
        }

        var categories = await productRepository.GetCategoriesByStoreAsync(tenantId, request.StoreId, false, cancellationToken);
        if (categories.Count <= 1)
        {
            throw new BusinessException(ErrorCodes.BadRequest, "至少保留一个分类");
        }

        await productRepository.DeleteCategoryAsync(request.CategoryId, tenantId, cancellationToken);
        await productRepository.SaveChangesAsync(cancellationToken);
    }
}
