using System.Security.Claims;

namespace GmRelay.Web.Services;

public static class ClaimsPrincipalExtensions
{
    public static bool TryGetTelegramId(this ClaimsPrincipal user, out long telegramId) =>
        long.TryParse(user.FindFirst("TelegramId")?.Value, out telegramId);

    public static bool TryGetDiscordId(this ClaimsPrincipal user, out string? discordId)
    {
        discordId = user.FindFirst("DiscordId")?.Value;
        return !string.IsNullOrWhiteSpace(discordId);
    }

    public static bool TryGetPlatformIdentity(this ClaimsPrincipal user, out string platform, out string externalUserId)
    {
        platform = string.Empty;
        externalUserId = string.Empty;

        var platformClaim = user.FindFirst("Platform")?.Value;
        if (!string.IsNullOrWhiteSpace(platformClaim))
        {
            platform = platformClaim;
            externalUserId = user.FindFirst(ClaimTypes.NameIdentifier)?.Value ?? string.Empty;
            return !string.IsNullOrWhiteSpace(externalUserId);
        }

        // Fallback for legacy Telegram users before Platform claim was added
        if (TryGetTelegramId(user, out var telegramId))
        {
            platform = "Telegram";
            externalUserId = telegramId.ToString(System.Globalization.CultureInfo.InvariantCulture);
            return true;
        }

        return false;
    }

    public static string? GetAvatarUrl(this ClaimsPrincipal user) =>
        user.FindFirst("AvatarUrl")?.Value;
}
