using System.Security.Claims;
using System.Text.Json.Serialization;

namespace ChessCubing.Server.Auth;

public sealed record LoginRequest(string Username, string Password);

public sealed record RegisterRequest(
    string Username,
    string Email,
    string Password,
    string ConfirmPassword,
    string? FirstName,
    string? LastName);

public sealed record ApiErrorResponse(string Message);

public sealed class AuthSessionResponse
{
    public bool IsAuthenticated { get; init; }

    public string? Subject { get; init; }

    public string? Username { get; init; }

    public string? Name { get; init; }

    public string? Email { get; init; }

    public string[] Roles { get; init; } = [];

    public static AuthSessionResponse FromUser(ClaimsPrincipal user)
        => new()
        {
            IsAuthenticated = user.Identity?.IsAuthenticated == true,
            Subject = user.FindFirst("sub")?.Value ?? user.FindFirst(ClaimTypes.NameIdentifier)?.Value,
            Username = user.FindFirst("preferred_username")?.Value ?? user.Identity?.Name,
            Name = user.FindFirst("name")?.Value ?? user.Identity?.Name,
            Email = user.FindFirst("email")?.Value,
            Roles = user.FindAll("role").Select(claim => claim.Value).Distinct(StringComparer.OrdinalIgnoreCase).ToArray(),
        };
}

public sealed class KeycloakUserInfo
{
    [JsonPropertyName("sub")]
    public string? Subject { get; init; }

    [JsonPropertyName("preferred_username")]
    public string? PreferredUsername { get; init; }

    [JsonPropertyName("name")]
    public string? Name { get; init; }

    [JsonPropertyName("email")]
    public string? Email { get; init; }

    public string[] Roles { get; set; } = [];
}
