using System;
using System.IO;
using StellaOps.Feedser.WebService.Options;
using Xunit;

namespace StellaOps.Feedser.WebService.Tests;

public sealed class FeedserOptionsPostConfigureTests
{
    [Fact]
    public void Apply_LoadsClientSecretFromRelativeFile()
    {
        var tempDirectory = Directory.CreateTempSubdirectory();
        try
        {
            var secretPath = Path.Combine(tempDirectory.FullName, "authority.secret");
            File.WriteAllText(secretPath, " feedser-secret ");

            var options = new FeedserOptions
            {
                Authority = new FeedserOptions.AuthorityOptions
                {
                    ClientSecretFile = "authority.secret"
                }
            };

            FeedserOptionsPostConfigure.Apply(options, tempDirectory.FullName);

            Assert.Equal("feedser-secret", options.Authority.ClientSecret);
        }
        finally
        {
            if (Directory.Exists(tempDirectory.FullName))
            {
                Directory.Delete(tempDirectory.FullName, recursive: true);
            }
        }
    }

    [Fact]
    public void Apply_ThrowsWhenSecretFileMissing()
    {
        var options = new FeedserOptions
        {
            Authority = new FeedserOptions.AuthorityOptions
            {
                ClientSecretFile = "missing.secret"
            }
        };

        var exception = Assert.Throws<InvalidOperationException>(() =>
            FeedserOptionsPostConfigure.Apply(options, AppContext.BaseDirectory));

        Assert.Contains("Authority client secret file", exception.Message);
    }
}
