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

namespace IamService.API.Application.Commands.Audit;

public record CreateAuditLogCommand(
    int EventTypeId,
    string ResourceType,
    Guid? ActorId = null,
    string? ActorEmail = null,
    Guid? ResourceId = null,
    string? Action = null,
    string? Details = null,
    string? IpAddress = null,
    string? UserAgent = null,
    bool Success = true) : IRequest<Guid>;

public class CreateAuditLogCommandHandler : IRequestHandler<CreateAuditLogCommand, Guid>
{
    private readonly IAuditLogRepository _repository;
    public CreateAuditLogCommandHandler(IAuditLogRepository repository) => _repository = repository;

    public async Task<Guid> Handle(CreateAuditLogCommand request, CancellationToken cancellationToken)
    {
        var eventType = AuditEventType.FromId(request.EventTypeId) ?? AuditEventType.Login;
        var log = AuditLog.Create(
            eventType, request.ResourceType, request.ActorId, request.ActorEmail,
            request.ResourceId, request.Action, request.Details, request.IpAddress, request.UserAgent, request.Success);
        _repository.Add(log);
        await _repository.UnitOfWork.SaveEntitiesAsync(cancellationToken);
        return log.Id;
    }
}
