using System.Net;
using Microsoft.Extensions.Configuration;
using Nexus.Api.Data;
using Nexus.Api.Integrations;
using Xunit;

namespace Nexus.Api.Tests;

public sealed class OpenClawRuntimeTests
{
    [Fact]
    public async Task GetStatusAsync_BlankPasswordFallsBackToConfiguredToken()
    {
        string? authorization = null;
        var configuration = new ConfigurationBuilder()
            .AddInMemoryCollection(new Dictionary<string, string?>
            {
                ["Integrations:OpenClaw:Password"] = string.Empty,
                ["Integrations:OpenClaw:Token"] = "gateway-token"
            })
            .Build();
        var client = new HttpClient(new StubHandler(request =>
        {
            authorization = request.Headers.Authorization?.ToString();
            return new HttpResponseMessage(HttpStatusCode.OK);
        }))
        {
            BaseAddress = new Uri("http://openclaw-gateway:18789")
        };
        var runtime = new OpenClawRuntime(client, configuration);

        var status = await runtime.GetStatusAsync(CancellationToken.None);

        Assert.Equal(OperationalStatus.Online, status.Status);
        Assert.Equal("Bearer gateway-token", authorization);
    }

    private sealed class StubHandler(
        Func<HttpRequestMessage, HttpResponseMessage> responder) : HttpMessageHandler
    {
        protected override Task<HttpResponseMessage> SendAsync(
            HttpRequestMessage request,
            CancellationToken cancellationToken)
            => Task.FromResult(responder(request));
    }
}
