using MediatR;
using Microsoft.Extensions.Logging;
using IamService.Domain.AggregatesModel.UserAggregate;

namespace IamService.API.Application.Queries.Users;

/// <summary>
/// EN: Handler for GetUsersQuery.
/// VI: Handler cho GetUsersQuery.
/// </summary>
public class GetUsersQueryHandler : IRequestHandler<GetUsersQuery, GetUsersQueryResult>
{
    private readonly IUserRepository _userRepository;
    private readonly ILogger<GetUsersQueryHandler> _logger;

    public GetUsersQueryHandler(
        IUserRepository userRepository,
        ILogger<GetUsersQueryHandler> logger)
    {
        _userRepository = userRepository ?? throw new ArgumentNullException(nameof(userRepository));
        _logger = logger ?? throw new ArgumentNullException(nameof(logger));
    }

    public async Task<GetUsersQueryResult> Handle(
        GetUsersQuery request,
        CancellationToken cancellationToken)
    {
        _logger.LogInformation(
            "Getting users page {PageNumber} with size {PageSize}",
            request.PageNumber, request.PageSize);

        var (users, totalCount) = await _userRepository.GetAllAsync(
            request.PageNumber,
            request.PageSize,
            cancellationToken);

        var userViewModels = users.Select(u => new UserViewModel(
            u.Id,
            u.Email!,
            u.FirstName,
            u.LastName,
            u.FullName,
            u.Status.Name,
            u.CreatedAt,
            u.LastLoginAt));

        return new GetUsersQueryResult(
            userViewModels,
            totalCount,
            request.PageNumber,
            request.PageSize);
    }
}
