using MediatR;
using TakeoutSaaS.Application.App.Tenants.Contracts;
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 (items, totalCount) = await tenantRepository.GetAuditLogsAsync(
            request.TenantId,
            request.Page,
            request.PageSize,
            cancellationToken);

        // 2. 转换为 DTO
        var dtos = items.Select(log => new TenantAuditLogDto
        {
            Id = log.Id,
            TenantId = log.TenantId,
            Action = log.Action,
            Title = log.Title,
            Description = log.Description,
            OperatorName = log.OperatorName,
            PreviousStatus = log.PreviousStatus,
            CurrentStatus = log.CurrentStatus,
            CreatedAt = log.CreatedAt
        }).ToList();

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