using System.Text.Json;

namespace Prospect.Server.Api.Services.Steam;

// Resolves a Steam persona (display) name from a SteamID64 via the Steam Web API.
// PlayFab does this server-side too; our emulator only gets the SteamID from the auth
// ticket, so the real name needs an API key. Inert (no-op) when no key is configured.
public class SteamWebApiService
{
    private static readonly HttpClient Http = new() { Timeout = TimeSpan.FromSeconds(5) };

    private readonly string? _apiKey;
    private readonly ILogger<SteamWebApiService> _logger;

    public SteamWebApiService(IConfiguration configuration, ILogger<SteamWebApiService> logger)
    {
        _apiKey = configuration["SteamWebApiKey"];
        _logger = logger;
    }

    public bool Enabled => !string.IsNullOrWhiteSpace(_apiKey);

    public async Task<string?> GetPersonaNameAsync(string steamId64)
    {
        if (!Enabled)
        {
            return null;
        }

        try
        {
            var url = $"https://api.steampowered.com/ISteamUser/GetPlayerSummaries/v2/?key={_apiKey}&steamids={steamId64}";
            var json = await Http.GetStringAsync(url);
            using var doc = JsonDocument.Parse(json);
            if (doc.RootElement.TryGetProperty("response", out var response) &&
                response.TryGetProperty("players", out var players) &&
                players.ValueKind == JsonValueKind.Array)
            {
                foreach (var player in players.EnumerateArray())
                {
                    if (player.TryGetProperty("personaname", out var name))
                    {
                        return name.GetString();
                    }
                }
            }
        }
        catch (Exception e)
        {
            _logger.LogWarning(e, "Steam GetPlayerSummaries failed for {SteamId}", steamId64);
        }

        return null;
    }
}
