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

namespace AutheliaMultiDomainProxy.Controllers;

[Controller]
public class LogoutController : Controller {
	[HttpPost]
	[Route("/api/logout")]
	[Produces("text/html")]
	public ActionResult Post([FromQuery] string rd) {
		// Check if we are on an allowed domain
		if (Vars.PermittedDomains.All(p => Request.Host.Host != $"{Vars.AuthProxySubdomain}.{p}"))
			return StatusCode(StatusCodes.Status421MisdirectedRequest);

		if (string.IsNullOrWhiteSpace(rd))
			rd = "/";

		Response.Cookies.Delete(Vars.CookieName, new CookieOptions { Secure = true, SameSite = SameSiteMode.Lax, HttpOnly = true, Domain = Request.Host.Host.Replace($"{Vars.AuthProxySubdomain}.", "")});
		Response.ContentType = "text/html";
		Response.Redirect(rd);
		return Content($"Cookie cleared. Redirecting... <a href=\"{rd}\">Click here if you are not redirected automatically</a>", "text/html");
	}
}
