using System.Text.Json;
using ClaudeDo.Worker.Config;
using ClaudeDo.Worker.Online;

namespace ClaudeDo.Worker.Tests.Online;

public sealed class OnlineInboxConfigTests : IDisposable
{
    private readonly string _configPath = Path.Combine(Path.GetTempPath(), $"worker_cfg_{Guid.NewGuid():N}.json");

    public void Dispose()
    {
        try { File.Delete(_configPath); } catch { }
    }

    [Fact]
    public void MissingSection_Returns_DisabledDefaults()
    {
        File.WriteAllText(_configPath, "{}");
        var cfg = WorkerConfig.Load(_configPath);

        Assert.False(cfg.OnlineInbox.Enabled);
        Assert.Equal("", cfg.OnlineInbox.ApiBaseUrl);
        Assert.Equal(60, cfg.OnlineInbox.PollIntervalSeconds);
        Assert.Equal("", cfg.OnlineInbox.Zitadel.Authority);
        Assert.Equal("", cfg.OnlineInbox.Zitadel.ClientId);
        Assert.Equal("openid offline_access", cfg.OnlineInbox.Zitadel.Scopes);
    }

    [Fact]
    public void MissingFile_Returns_DisabledDefaults()
    {
        var cfg = WorkerConfig.Load(Path.Combine(Path.GetTempPath(), $"nonexistent_{Guid.NewGuid():N}.json"));

        Assert.False(cfg.OnlineInbox.Enabled);
        Assert.Equal(60, cfg.OnlineInbox.PollIntervalSeconds);
    }

    [Fact]
    public void PopulatedSection_RoundTrips()
    {
        var json = """
            {
                "online_inbox": {
                    "enabled": true,
                    "api_base_url": "https://inbox.claudedo.kuns.dev",
                    "poll_interval_seconds": 120,
                    "zitadel": {
                        "authority": "https://auth.example.com",
                        "client_id": "abc123",
                        "scopes": "openid offline_access profile"
                    }
                }
            }
            """;
        File.WriteAllText(_configPath, json);
        var cfg = WorkerConfig.Load(_configPath);

        Assert.True(cfg.OnlineInbox.Enabled);
        Assert.Equal("https://inbox.claudedo.kuns.dev", cfg.OnlineInbox.ApiBaseUrl);
        Assert.Equal(120, cfg.OnlineInbox.PollIntervalSeconds);
        Assert.Equal("https://auth.example.com", cfg.OnlineInbox.Zitadel.Authority);
        Assert.Equal("abc123", cfg.OnlineInbox.Zitadel.ClientId);
        Assert.Equal("openid offline_access profile", cfg.OnlineInbox.Zitadel.Scopes);
    }

    [Fact]
    public void PartialSection_UsesDefaultsForMissingFields()
    {
        var json = """{"online_inbox": {"enabled": true}}""";
        File.WriteAllText(_configPath, json);
        var cfg = WorkerConfig.Load(_configPath);

        Assert.True(cfg.OnlineInbox.Enabled);
        Assert.Equal("", cfg.OnlineInbox.ApiBaseUrl);
        Assert.Equal(60, cfg.OnlineInbox.PollIntervalSeconds);
    }
}
