defmodule CentralcloudStaff.SessionController do
  use Phoenix.Controller, formats: [:html]
  import Plug.Conn

  def new(conn, _params) do
    case header(conn, "x-authentik-username") do
      nil ->
        conn
        |> put_resp_content_type("text/html")
        |> send_resp(401, no_headers_page())

      username ->
        conn
        |> put_session(:staff_id, username)
        |> put_session(:staff_email, header(conn, "x-authentik-email"))
        |> put_session(:staff_name, header(conn, "x-authentik-name"))
        |> put_session(:staff_groups, header(conn, "x-authentik-groups", "") |> String.split(",", trim: true))
        |> redirect(to: "/")
    end
  end

  def delete(conn, _params) do
    conn
    |> clear_session()
    |> redirect(to: "/outpost.goauthentik.io/sign_out")
  end

  defp header(conn, name, default \\ nil) do
    case get_req_header(conn, name) do
      [v | _] -> v
      [] -> default
    end
  end

  defp no_headers_page do
    """
    <!DOCTYPE html>
    <html lang="en"><head><meta charset="utf-8"/><title>Auth error</title></head>
    <body style="font-family:sans-serif;padding:2rem;background:#0a0f1e;color:#e2e8f0">
    <h1>Authentication missing</h1>
    <p>No <code>X-authentik-*</code> headers were received. This request did not pass
    through the Authentik forward-auth outpost. Check the IngressRoute middleware.</p>
    </body></html>
    """
  end
end
