using LiteCqrs;
using TeleWave.Application.Common.Interfaces;
using TeleWave.Application.Common.Models;

namespace TeleWave.Application.Auth.Me;

public sealed class GetCurrentUserQueryHandler(
    IIdentityService identityService,
    ICurrentUser currentUser
) : IQueryHandler<GetCurrentUserQuery, Result<CurrentUserDto>>
{
    public async Task<Result<CurrentUserDto>> Handle(
        GetCurrentUserQuery query,
        CancellationToken cancellationToken
    )
    {
        if (currentUser.UserId is not { } userId)
            return Result.Failure<CurrentUserDto>(AuthErrors.Unauthorized);

        var profile = await identityService.GetProfileAsync(userId, cancellationToken);
        if (profile is null)
            return Result.Failure<CurrentUserDto>(AuthErrors.Unauthorized);

        return Result.Success(new CurrentUserDto(profile.Id, profile.UserName, profile.Role));
    }
}
