using MediatR;
using TakeoutSaaS.Application.App.Merchants.Dto;
using TakeoutSaaS.Application.App.Merchants.Queries;
using TakeoutSaaS.Domain.Merchants.Repositories;
using TakeoutSaaS.Shared.Abstractions.Constants;
using TakeoutSaaS.Shared.Abstractions.Exceptions;

namespace TakeoutSaaS.Application.App.Merchants.Handlers;

/// <summary>
/// 商户审核历史处理器。
/// </summary>
public sealed class GetMerchantAuditHistoryQueryHandler(
    IMerchantRepository merchantRepository)
    : IRequestHandler<GetMerchantAuditHistoryQuery, IReadOnlyList<MerchantAuditLogDto>>
{
    /// <inheritdoc />
    public async Task<IReadOnlyList<MerchantAuditLogDto>> Handle(
        GetMerchantAuditHistoryQuery request,
        CancellationToken cancellationToken)
    {
        // 1. 查询商户（跨租户）
        var merchant = await merchantRepository.FindByIdAsync(request.MerchantId, cancellationToken);
        if (merchant == null)
        {
            throw new BusinessException(ErrorCodes.NotFound, "商户不存在");
        }

        // 2. (空行后) 查询审核历史
        var logs = await merchantRepository.GetAuditLogsAsync(merchant.Id, merchant.TenantId, cancellationToken);
        return logs.Select(MerchantMapping.ToDto).ToList();
    }
}
