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

namespace TakeoutSaaS.Application.App.Merchants.Handlers;

/// <summary>
/// 删除类目处理器。
/// </summary>
public sealed class DeleteMerchantCategoryCommandHandler(
    IMerchantCategoryRepository categoryRepository,
    ITenantProvider tenantProvider)
    : IRequestHandler<DeleteMerchantCategoryCommand, bool>
{
    /// <summary>
    /// 处理删除类目请求。
    /// </summary>
    /// <param name="request">删除命令。</param>
    /// <param name="cancellationToken">取消标记。</param>
    /// <returns>执行结果。</returns>
    public async Task<bool> Handle(DeleteMerchantCategoryCommand request, CancellationToken cancellationToken)
    {
        // 1. 获取租户上下文
        var tenantId = tenantProvider.GetCurrentTenantId();
        var existing = await categoryRepository.FindByIdAsync(request.CategoryId, tenantId, cancellationToken);

        if (existing == null)
        {
            return false;
        }

        // 2. 删除并保存
        await categoryRepository.RemoveAsync(existing, cancellationToken);
        await categoryRepository.SaveChangesAsync(cancellationToken);
        return true;
    }
}
