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;
using TakeoutSaaS.Shared.Abstractions.Tenancy;

namespace TakeoutSaaS.Application.App.Merchants.Handlers;

/// <summary>
/// 商户审核历史处理器。
/// </summary>
public sealed class GetMerchantAuditHistoryQueryHandler(
    IMerchantRepository merchantRepository,
    ITenantProvider tenantProvider)
    : IRequestHandler<GetMerchantAuditHistoryQuery, IReadOnlyList<MerchantAuditLogDto>>
{
    /// <inheritdoc />
    public async Task<IReadOnlyList<MerchantAuditLogDto>> Handle(
        GetMerchantAuditHistoryQuery request,
        CancellationToken cancellationToken)
    {
        var currentTenantId = tenantProvider.GetCurrentTenantId();
        var merchant = await merchantRepository.FindByIdAsync(request.MerchantId, currentTenantId, cancellationToken);

        if (merchant == null)
        {
            throw new BusinessException(ErrorCodes.NotFound, "商户不存在");
        }

        var logs = await merchantRepository.GetAuditLogsAsync(merchant.Id, merchant.TenantId, cancellationToken);
        return logs.Select(MerchantMapping.ToDto).ToList();
    }
}
