using AutheliaMultiDomainProxy.Backend;
using Microsoft.AspNetCore.Mvc;

namespace AutheliaMultiDomainProxy.Controllers; 

[Controller]
[Route("/api/verify")]
public class VerifyController : Controller {
	public string Get() {
		// Check if we are on an allowed domain
		if (!Vars.PermittedDomains.Any(p => Request.Host.Host.EndsWith($".{p}"))) {
			Response.StatusCode = 421;
			return "421 Misdirected Request";
		}

		var upstreamResponse = AuthHelpers.MakeUpstreamAutheliaRequest(Request.Headers, Request.Cookies[Vars.CookieName]);

		foreach (var header in upstreamResponse.Headers) {
			if (Vars.ResponseHeaders.Contains(header.Key, StringComparer.InvariantCultureIgnoreCase))
				foreach (var s in header.Value)
					Response.Headers.Add(header.Key, s);
		}

		Response.StatusCode = (int)upstreamResponse.StatusCode;
		return upstreamResponse.Content.ReadAsStringAsync().Result;
	}
}
