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

namespace TakeoutSaaS.Application.App.Merchants.Handlers;

/// <summary>
/// 读取商户审核日志。
/// </summary>
public sealed class GetMerchantAuditLogsQueryHandler(
    IMerchantRepository merchantRepository)
    : 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 merchant = await merchantRepository.FindByIdAsync(request.MerchantId, cancellationToken);
        if (merchant is null)
        {
            return new PagedResult<MerchantAuditLogDto>([], request.Page, request.PageSize, 0);
        }

        // 2. (空行后) 查询日志
        var logs = await merchantRepository.GetAuditLogsAsync(request.MerchantId, merchant.TenantId, cancellationToken);
        var total = logs.Count;

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

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