using Application.Auth.DTOs;
using Domain.Ports.Repositories;
using HotChocolate.Authorization;
using System.Security.Claims;

namespace Adapters.Driving.Api.Types.Auth;

[ExtendObjectType(typeof(Query))]
public class AuthQueries
{
    /// <summary>
    /// Returns the current authenticated user's information.
    /// </summary>
    [Authorize]
    public async Task<UserInfo?> Me(
        ClaimsPrincipal user,
        [Service] IUserRepository userRepository,
        CancellationToken ct)
    {
        var userIdClaim = user.FindFirst(ClaimTypes.NameIdentifier)?.Value;
        if (userIdClaim is null || !int.TryParse(userIdClaim, out var userId))
            return null;

        var dbUser = await userRepository.GetByIdAsync(userId, ct);
        if (dbUser is null)
            return null;

        return new UserInfo(
            dbUser.Id,
            dbUser.Username,
            dbUser.Role,
            dbUser.StudentId,
            dbUser.Student?.Name
        );
    }
}
