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

namespace TakeoutSaaS.Application.App.Tenants.Handlers;

/// <summary>
/// 审核日志查询。
/// </summary>
public sealed class GetTenantAuditLogsQueryHandler(ITenantRepository tenantRepository)
    : IRequestHandler<GetTenantAuditLogsQuery, PagedResult<TenantAuditLogDto>>
{
    /// <inheritdoc />
    public async Task<PagedResult<TenantAuditLogDto>> Handle(GetTenantAuditLogsQuery request, CancellationToken cancellationToken)
    {
        // 1. 查询审核日志
        var logs = await tenantRepository.GetAuditLogsAsync(request.TenantId, cancellationToken);
        var total = logs.Count;

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

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