using MediatR;
using TakeoutSaaS.Application.App.Merchants.Dto;
using TakeoutSaaS.Application.App.Merchants.Queries;
using TakeoutSaaS.Domain.Merchants.Repositories;
using TakeoutSaaS.Shared.Abstractions.Results;
using TakeoutSaaS.Shared.Abstractions.Tenancy;

namespace TakeoutSaaS.Application.App.Merchants.Handlers;

/// <summary>
/// 读取商户审核日志。
/// </summary>
public sealed class GetMerchantAuditLogsQueryHandler(
    IMerchantRepository merchantRepository,
    ITenantProvider tenantProvider)
    : IRequestHandler<GetMerchantAuditLogsQuery, PagedResult<MerchantAuditLogDto>>
{
    /// <summary>
    /// 查询商户审核日志列表。
    /// </summary>
    /// <param name="request">查询请求。</param>
    /// <param name="cancellationToken">取消标记。</param>
    /// <returns>分页结果。</returns>
    public async Task<PagedResult<MerchantAuditLogDto>> Handle(GetMerchantAuditLogsQuery request, CancellationToken cancellationToken)
    {
        // 1. 获取租户上下文并查询日志
        var tenantId = tenantProvider.GetCurrentTenantId();
        var logs = await merchantRepository.GetAuditLogsAsync(request.MerchantId, tenantId, cancellationToken);
        var total = logs.Count;

        // 2. 分页映射
        var paged = logs
            .Skip((request.Page - 1) * request.PageSize)
            .Take(request.PageSize)
            .Select(MerchantMapping.ToDto)
            .ToList();

        // 3. 返回结果
        return new PagedResult<MerchantAuditLogDto>(paged, request.Page, request.PageSize, total);
    }
}
