using MediatR;
using Microsoft.Extensions.Logging;
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 DeleteMerchantCommandHandler(
    IMerchantRepository merchantRepository,
    ITenantProvider tenantProvider,
    ILogger<DeleteMerchantCommandHandler> logger)
    : IRequestHandler<DeleteMerchantCommand, bool>
{
    /// <inheritdoc />
    public async Task<bool> Handle(DeleteMerchantCommand request, CancellationToken cancellationToken)
    {
        // 1. 校验存在性
        var tenantId = tenantProvider.GetCurrentTenantId();
        var existing = await merchantRepository.FindByIdAsync(request.MerchantId, tenantId, cancellationToken);
        if (existing == null)
        {
            return false;
        }

        // 2. 删除
        await merchantRepository.DeleteMerchantAsync(request.MerchantId, tenantId, cancellationToken);
        await merchantRepository.SaveChangesAsync(cancellationToken);
        logger.LogInformation("删除商户 {MerchantId}", request.MerchantId);

        return true;
    }
}
