using System.Net;
using ClawdDotNet.Core.Deploymentcenter;
using Shouldly;

namespace ClawdDotNet.Core.Tests.Deploymentcenter;

public sealed class TokenProvisionerTests
{
    [Fact]
    public async Task Instanz_bekommt_ein_eigenes_Sub_Token()
    {
        var handler = new CapturingHandler(HttpStatusCode.Created,
            """
            {"status":"success","sub_token":"dc_sub_abc","token_id":"tok_s_1",
             "scopes":["watchdog:ping","bugtracker:report"]}
            """);

        using var api = new DeploymentcenterApi("https://dc.example", "master", new HttpClient(handler));

        var token = await new TokenProvisioner(api).ProvisionAsync(
            "ClawdDotNet Produktion", "inst-1", TokenProvisioner.InstanceScopes);

        handler.LastRequest!.RequestUri!.ToString().ShouldBe("https://dc.example/api/tokens/v1/provision");
        handler.LastRequest.Headers.Authorization!.ToString().ShouldBe("Bearer master");
        handler.LastBody!.ShouldContain("\"instance_id\":\"inst-1\"");
        handler.LastBody.ShouldContain("watchdog:ping");

        token.Token.ShouldBe("dc_sub_abc");
        token.TokenId.ShouldBe("tok_s_1");
        token.Scopes.ShouldContain("bugtracker:report");
    }

    /// <summary>
    /// Ein Sub-Token darf keine weiteren ausstellen. Das ist der Regelfall beim zweiten
    /// Start und muss als sauberer Fehler herauskommen, nicht als Absturz.
    /// </summary>
    [Fact]
    public async Task Abgelehnte_Provisionierung_wirft_mit_Code()
    {
        var handler = new CapturingHandler(HttpStatusCode.Forbidden,
            """{"status":"error","error":{"code":"provision_denied","message":"Kein Master-Token."}}""");

        using var api = new DeploymentcenterApi("https://dc.example", "sub", new HttpClient(handler));

        var ex = await Should.ThrowAsync<DeploymentcenterException>(
            () => new TokenProvisioner(api).ProvisionAsync("x", "inst-1", ["watchdog:ping"]));

        ex.Code.ShouldBe("provision_denied");
    }
}
