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

namespace AutheliaMultiDomainProxy.Controllers;

[Controller]
[Route("/api/redirect")]
public class RedirectController : Controller {
	public IActionResult Get([FromQuery] string tgt) {
		// 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)) {
			Response.StatusCode = StatusCodes.Status421MisdirectedRequest;
			return BadRequest("Bad request.");
		}

		// tgt is urlencoded twice because authelia decodes it by one layer 
		var targetUrl =
			$"https://https://{Vars.AuthProxySubdomain}.{dstDomain}/api/cookieproxy_stage_one?tgt={HttpUtility.UrlEncode(HttpUtility.UrlEncode(tgt))}";
		Response.Redirect(targetUrl);
		return Content($"Redirecting... <a href=\"{targetUrl}\">Click here if you are not redirected automatically</a>", "text/html");
	}
}
