using System.Net.Http.Json;
using System.Text.Json;

namespace GameList.Tests.Support;

internal static class TestClientExtensions
{
    public static Task<HttpResponseMessage> RegisterAsync(this HttpClient client, string username, bool admin = false)
    {
        return client.PostAsJsonAsync("/api/auth/register", new
        {
            Username = username,
            Password = "Pass123!",
            DisplayName = $"{username}-name",
            AdminKey = admin ? "admin-key" : null
        });
    }

    public static Task<HttpResponseMessage> LoginAsync(this HttpClient client, string username, string password)
    {
        return client.PostAsJsonAsync("/api/auth/login", new
        {
            Username = username,
            Password = password
        });
    }

    public static async Task<int> CreateSuggestionAsync(this HttpClient client, string name)
    {
        var response = await client.PostAsJsonAsync("/api/suggestions", new
        {
            Name = name,
            Genre = "Coop",
            Description = (string?)null,
            ScreenshotUrl = (string?)null,
            YoutubeUrl = (string?)null,
            GameUrl = (string?)null,
            MinPlayers = (int?)null,
            MaxPlayers = (int?)null
        });

        response.EnsureSuccessStatusCode();
        var json = await response.Content.ReadFromJsonAsync<JsonElement>();
        return json.GetProperty("id").GetInt32();
    }

    public static async Task<Guid> GetProfileIdAsync(this HttpClient client)
    {
        var me = await client.GetFromJsonAsync<JsonElement>("/api/me");
        return Guid.Parse(me.GetProperty("id").GetString()!);
    }
}
