using MediatR;
using Microsoft.Extensions.Logging;
using TakeoutSaaS.Application.App.Merchants.Commands;
using TakeoutSaaS.Domain.Merchants.Repositories;

namespace TakeoutSaaS.Application.App.Merchants.Handlers;

/// <summary>
/// 删除商户命令处理器。
/// </summary>
public sealed class DeleteMerchantCommandHandler(
    IMerchantRepository merchantRepository,
    ILogger<DeleteMerchantCommandHandler> logger)
    : IRequestHandler<DeleteMerchantCommand, bool>
{
    /// <inheritdoc />
    public async Task<bool> Handle(DeleteMerchantCommand request, CancellationToken cancellationToken)
    {
        // 1. 校验存在性（跨租户）
        var existing = await merchantRepository.FindByIdAsync(request.MerchantId, cancellationToken);
        if (existing == null)
        {
            return false;
        }

        // 2. (空行后) 删除
        await merchantRepository.DeleteMerchantAsync(request.MerchantId, existing.TenantId, cancellationToken);
        await merchantRepository.SaveChangesAsync(cancellationToken);
        logger.LogInformation("删除商户 {MerchantId}", request.MerchantId);

        return true;
    }
}
