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 GetMerchantChangeHistoryQueryHandler(
    IMerchantRepository merchantRepository)
    : IRequestHandler<GetMerchantChangeHistoryQuery, IReadOnlyList<MerchantChangeLogDto>>
{
    /// <inheritdoc />
    public async Task<IReadOnlyList<MerchantChangeLogDto>> Handle(
        GetMerchantChangeHistoryQuery 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.GetChangeLogsAsync(merchant.Id, merchant.TenantId, request.FieldName, cancellationToken);
        return logs.Select(MerchantMapping.ToDto).ToList();
    }
}
