using FastGithub.ReverseProxy;
using FastGithub.Scanner;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
using System.Net.Http;
using Yarp.ReverseProxy.Forwarder;
namespace FastGithub
{
    /// 
    /// gitub反向代理的中间件扩展
    /// 
    public static class ReverseProxyApplicationBuilderExtensions
    {
        /// 
        /// 使用gitub反向代理中间件
        /// 
        /// 
        /// 
        public static IApplicationBuilder UseGithubReverseProxy(this IApplicationBuilder app)
        {
            var httpForwarder = app.ApplicationServices.GetRequiredService();
            var httpClientHanlder = app.ApplicationServices.GetRequiredService();
            var lookupOptions = app.ApplicationServices.GetRequiredService>();
            var options = app.ApplicationServices.GetRequiredService>();
            app.Use(next => async context =>
            {
                var host = context.Request.Host.Host;
                if (lookupOptions.CurrentValue.Domains.Contains(host) == false)
                {
                    await context.Response.WriteAsJsonAsync(new { message = $"不支持以{host}访问" });
                }
                else
                {
                    var port = context.Request.Host.Port ?? 443;
                    var destinationPrefix = $"http://{host}:{port}/";
                    var httpClient = new HttpMessageInvoker(httpClientHanlder, disposeHandler: false);
                    var requestConfig = options.CurrentValue.ForwarderRequestConfig;
                    await httpForwarder.SendAsync(context, destinationPrefix, httpClient, requestConfig);
                }
            });
            return app;
        }
    }
}