using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.HttpOverrides;
using Microsoft.Extensions.Configuration;

namespace JobTrackerApi.Services;

public static class ForwardedProxyConfiguration
{
    public static ForwardedHeadersOptions Build(IConfiguration configuration)
    {
        var networks = (configuration.GetSection("Proxy:KnownNetworks").Get<string[]>() ?? Array.Empty<string>())
            .Select(x => x?.Trim())
            .Where(x => !string.IsNullOrEmpty(x))
            .ToArray();
        if (networks.Length == 0)
            throw new InvalidOperationException("Proxy:KnownNetworks must contain the nginx proxy CIDR when forwarded headers are enabled.");

        var options = new ForwardedHeadersOptions
        {
            ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto,
            ForwardLimit = 1,
        };
        options.KnownNetworks.Clear();
        options.KnownProxies.Clear();

        foreach (var value in networks)
        {
            if (!IPNetwork.TryParse(value, out var network))
                throw new InvalidOperationException($"Proxy:KnownNetworks contains an invalid CIDR: {value}");

            options.KnownNetworks.Add(network);
        }

        return options;
    }
}
