using System;
using System.IO;

namespace StellaOps.Feedser.WebService.Options;

/// <summary>
/// Post-configuration helpers for <see cref="FeedserOptions"/>.
/// </summary>
public static class FeedserOptionsPostConfigure
{
    /// <summary>
    /// Applies derived settings that require filesystem access, such as loading client secrets from disk.
    /// </summary>
    /// <param name="options">The options to mutate.</param>
    /// <param name="contentRootPath">Application content root used to resolve relative paths.</param>
    public static void Apply(FeedserOptions options, string contentRootPath)
    {
        ArgumentNullException.ThrowIfNull(options);

        options.Authority ??= new FeedserOptions.AuthorityOptions();

        var authority = options.Authority;
        if (string.IsNullOrWhiteSpace(authority.ClientSecret)
            && !string.IsNullOrWhiteSpace(authority.ClientSecretFile))
        {
            var resolvedPath = authority.ClientSecretFile!;
            if (!Path.IsPathRooted(resolvedPath))
            {
                resolvedPath = Path.Combine(contentRootPath, resolvedPath);
            }

            if (!File.Exists(resolvedPath))
            {
                throw new InvalidOperationException($"Authority client secret file '{resolvedPath}' was not found.");
            }

            var secret = File.ReadAllText(resolvedPath).Trim();
            if (string.IsNullOrEmpty(secret))
            {
                throw new InvalidOperationException($"Authority client secret file '{resolvedPath}' is empty.");
            }

            authority.ClientSecret = secret;
        }
    }
}
