using MediatR;
using Microsoft.AspNetCore.Identity;
using SolutionErp.Application.Auth.Dtos;
using SolutionErp.Application.Common.Exceptions;
using SolutionErp.Application.Common.Interfaces;
using SolutionErp.Domain.Identity;

namespace SolutionErp.Application.Auth.Queries.Me;

public record GetMeQuery : IRequest<UserInfoDto>;

public class GetMeQueryHandler : IRequestHandler<GetMeQuery, UserInfoDto>
{
    private readonly ICurrentUser _currentUser;
    private readonly UserManager<User> _userManager;

    public GetMeQueryHandler(ICurrentUser currentUser, UserManager<User> userManager)
    {
        _currentUser = currentUser;
        _userManager = userManager;
    }

    public async Task<UserInfoDto> Handle(GetMeQuery request, CancellationToken cancellationToken)
    {
        if (!_currentUser.IsAuthenticated || _currentUser.UserId is null)
            throw new UnauthorizedException();

        var user = await _userManager.FindByIdAsync(_currentUser.UserId.Value.ToString())
            ?? throw new UnauthorizedException();

        var roles = await _userManager.GetRolesAsync(user);
        return new UserInfoDto(user.Id, user.Email!, user.FullName, roles.ToList());
    }
}
