using System.Web;
using AutheliaMultiDomainProxy.Backend;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Net.Http.Headers;
using SameSiteMode = Microsoft.AspNetCore.Http.SameSiteMode;

namespace AutheliaMultiDomainProxy.Controllers;

[Controller]
public class CookieProxyController : Controller {
	[Produces("text/html", "text/plain")]
	[Route("/api/cookieproxy_stage_one")]
	public IActionResult StageOne([FromQuery] string tgt) {
		// Check if we are on the correct domain
		if (Request.Host.Host != $"{Vars.AuthProxySubdomain}.{Vars.UpstreamPrimaryDomain}")
			return StatusCode(StatusCodes.Status421MisdirectedRequest);

		var dstDomain = AuthHelpers.GetRootDomain(tgt);

		if (!Request.Cookies.ContainsKey("authelia_session") || string.IsNullOrWhiteSpace(tgt) || !Vars.PermittedDomains.Contains(dstDomain)) {
			return BadRequest("Bad request.");
		}

		var targetUrl = $"https://{Vars.AuthProxySubdomain}.{dstDomain}/api/cookieproxy_stage_two?tgt={HttpUtility.UrlEncode(tgt)}";
		return
			Content($"Redirecting to cookie proxy (stage two) on the destination domain... <form method=\"POST\" action=\"{targetUrl}\"> <input type=\"hidden\" name=\"cookie\" value=\"{HttpUtility.HtmlEncode(Request.Cookies["authelia_session"])}\"><button type=\"submit\">Click here</button> if you are not redirected automatically</form><script>document.querySelector(\"form\").submit();</script>",
				    "text/html");
	}

	[HttpPost]
	[Produces("text/html", "text/plain")]
	[Route("/api/cookieproxy_stage_two")]
	public IActionResult StageTwo([FromQuery] string tgt, [FromForm] string cookie) {
		// Check if we are on an allowed domain
		if (Vars.PermittedDomains.All(p => Request.Host.Host != $"{Vars.AuthProxySubdomain}.{p}"))
			return StatusCode(StatusCodes.Status421MisdirectedRequest);

		var dstDomain = AuthHelpers.GetRootDomain(tgt);

		if (string.IsNullOrWhiteSpace(tgt) || !Vars.PermittedDomains.Contains(dstDomain) || string.IsNullOrWhiteSpace(cookie)) {
			return BadRequest("Bad request.");
		}

		Response.Cookies.Append(Vars.CookieName, cookie,
							    new CookieOptions {
								    Expires  = DateTimeOffset.Now + TimeSpan.FromDays(365),
								    SameSite = SameSiteMode.Lax,
								    Secure   = true,
								    HttpOnly = true,
								    Domain   = dstDomain
							    });
		Response.Redirect(tgt);
		return Content($"Cookie set. Redirecting... <a href=\"{tgt}\">Click here if you are not redirected automatically</a>", "text/html");
	}
}
