using System.Net;
using System.Text.Json;
using UniVerse.Api.Tests.Helpers;
using Xunit;

namespace UniVerse.Api.Tests.Swagger;

public class SwaggerDocumentTests : IClassFixture<ApiWebApplicationFactory>
{
    private readonly HttpClient _client;

    public SwaggerDocumentTests(ApiWebApplicationFactory factory)
    {
        _client = factory.CreateClient();
    }

    [Fact]
    public async Task SwaggerJson_IsGenerated()
    {
        var response = await _client.GetAsync("api/docs/v1/swagger.json");

        Assert.Equal(HttpStatusCode.OK, response.StatusCode);

        using var document = JsonDocument.Parse(await response.Content.ReadAsStringAsync());
        var root = document.RootElement;

        Assert.Equal("UniVerse API", root.GetProperty("info").GetProperty("title").GetString());
        Assert.True(root.GetProperty("components").GetProperty("securitySchemes").TryGetProperty("Bearer", out _));
    }

    [Fact]
    public async Task SwaggerJson_DocumentsSecurityOnlyForAuthorizedEndpoints()
    {
        using var document = JsonDocument.Parse(await _client.GetStringAsync("api/docs/v1/swagger.json"));
        var paths = document.RootElement.GetProperty("paths");

        var publicOperation = paths
            .GetProperty("/api/v1/auth/login/dev")
            .GetProperty("post");
        var protectedOperation = paths
            .GetProperty("/api/v1/users")
            .GetProperty("get");

        Assert.False(publicOperation.TryGetProperty("security", out _));
        Assert.True(protectedOperation.TryGetProperty("security", out var security));
        Assert.Equal("Bearer", security[0].EnumerateObject().Single().Name);
        Assert.Contains("Required roles:", protectedOperation.GetProperty("description").GetString());
    }
}
