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