using MediatR;
using IamService.Domain.AggregatesModel.AuditAggregate;

namespace IamService.API.Application.Queries.Audit;

public record GetAuditLogsQuery(
    DateTime? FromDate = null,
    DateTime? ToDate = null,
    int? EventTypeId = null,
    Guid? ActorId = null,
    string? ResourceType = null,
    int Skip = 0,
    int Take = 50) : IRequest<AuditLogsResult>;

public record AuditLogsResult(IEnumerable<AuditLogDto> Logs, long TotalCount);

public record AuditLogDto(
    Guid Id,
    string EventType,
    Guid? ActorId,
    string? ActorEmail,
    string ResourceType,
    Guid? ResourceId,
    string? Action,
    bool Success,
    DateTime Timestamp);

public class GetAuditLogsQueryHandler : IRequestHandler<GetAuditLogsQuery, AuditLogsResult>
{
    private readonly IAuditLogRepository _repository;
    public GetAuditLogsQueryHandler(IAuditLogRepository repository) => _repository = repository;

    public async Task<AuditLogsResult> Handle(GetAuditLogsQuery request, CancellationToken cancellationToken)
    {
        var logs = await _repository.SearchAsync(
            request.FromDate, request.ToDate, request.EventTypeId, request.ActorId,
            request.ResourceType, request.Skip, request.Take, cancellationToken);
        var count = await _repository.GetCountAsync(request.FromDate, request.ToDate, cancellationToken);

        var dtos = logs.Select(l => new AuditLogDto(
            l.Id, l.EventType.Name, l.ActorId, l.ActorEmail, l.ResourceType,
            l.ResourceId, l.Action, l.Success, l.Timestamp));
        return new AuditLogsResult(dtos, count);
    }
}
