using ColaFlow.Modules.ProjectManagement.Domain.Repositories;
using MediatR;

namespace ColaFlow.Modules.ProjectManagement.Application.Queries.AuditLogs.GetRecentAuditLogs;

/// <summary>
/// Handler for GetRecentAuditLogsQuery
/// Retrieves the most recent audit log entries across all entities
/// Results are automatically filtered by tenant via global query filter
/// </summary>
public class GetRecentAuditLogsQueryHandler(IAuditLogRepository auditLogRepository)
    : IRequestHandler<GetRecentAuditLogsQuery, IReadOnlyList<AuditLogDto>>
{
    public async Task<IReadOnlyList<AuditLogDto>> Handle(GetRecentAuditLogsQuery request, CancellationToken cancellationToken)
    {
        var auditLogs = await auditLogRepository.GetRecentAsync(request.Count, cancellationToken);

        return auditLogs
            .Select(a => new AuditLogDto(
                a.Id,
                a.EntityType,
                a.EntityId,
                a.Action,
                a.UserId?.Value,
                a.Timestamp,
                a.OldValues,
                a.NewValues
            ))
            .ToList();
    }
}
