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

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

/// <summary>
/// Handler for GetAuditLogsByEntityQuery
/// Retrieves all audit log entries for a specific entity (e.g., all changes to a Project)
/// Results are automatically filtered by tenant via global query filter
/// </summary>
public class GetAuditLogsByEntityQueryHandler(IAuditLogRepository auditLogRepository)
    : IRequestHandler<GetAuditLogsByEntityQuery, IReadOnlyList<AuditLogDto>>
{
    public async Task<IReadOnlyList<AuditLogDto>> Handle(GetAuditLogsByEntityQuery request, CancellationToken cancellationToken)
    {
        var auditLogs = await auditLogRepository.GetByEntityAsync(
            request.EntityType,
            request.EntityId,
            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();
    }
}
