using System.Web;
using Nager.PublicSuffix;

namespace AutheliaMultiDomainProxy.Backend;

public class AuthHelpers {
	static DomainParser domainParser = new DomainParser(new WebTldRuleProvider());

	public static (bool isAuthenticated, string? user) IsAuthenticated(IRequestCookieCollection cookies) {
		if (!cookies.ContainsKey(Vars.CookieName))
			return (false, null);

		var response = MakeUpstreamAutheliaRequest(cookies[Vars.CookieName]!);

		if (!response.IsSuccessStatusCode)
			return (false, null);

		return response.Headers.Contains("remote-user") ? (true, response.Headers.GetValues("remote-user").First()) : (true, null);
	}

	private static HttpResponseMessage MakeUpstreamAutheliaRequest(string cookie) {
		var client = new HttpClient();
		client.DefaultRequestHeaders.Add("cookie", $"authelia_session={cookie}");
		client.DefaultRequestHeaders.Add("x-forwarded-proto", "https");
		client.DefaultRequestHeaders.Add("Host", $"{Vars.AutheliaSubdomain}.{Vars.UpstreamPrimaryDomain}");
		var response = client.GetAsync($"http://127.0.0.1:9091/api/verify");
		return response.Result;
	}
	
	public static HttpResponseMessage MakeUpstreamAutheliaRequest(IHeaderDictionary headers, string? cookie) {
		var client = new HttpClient();

		foreach (var header in headers) {
			if (Vars.RequestHeaders.Contains(header.Key, StringComparer.InvariantCultureIgnoreCase))
				client.DefaultRequestHeaders.Add(header.Key, (IEnumerable<string?>)header.Value);
		}

		client.DefaultRequestHeaders.Host = $"{headers["Host"]}.amdp.{Vars.UpstreamPrimaryDomain}";

		if (!string.IsNullOrWhiteSpace(cookie))
			client.DefaultRequestHeaders.Add("cookie", $"authelia_session={cookie}");
		
		var response = client.GetAsync($"http://127.0.0.1:9091/api/verify");
		return response.Result;
	}

	public static string GetRootDomain(string url) {
		return domainParser.Parse(new Uri(url).Host).RegistrableDomain;
	}
}
