defmodule MvWeb.LocaleController do
  use MvWeb, :controller

  @supported_locales ["de", "en"]

  def set_locale(conn, %{"locale" => locale}) when locale in @supported_locales do
    conn
    |> put_session(:locale, locale)
    |> put_resp_cookie("locale", locale,
      max_age: 365 * 24 * 60 * 60,
      same_site: "Lax",
      http_only: true,
      secure: Application.get_env(:mv, :use_secure_cookies, false)
    )
    |> redirect(to: get_referer(conn) || "/")
  end

  def set_locale(conn, _params), do: redirect(conn, to: get_referer(conn) || "/")

  defp get_referer(conn) do
    conn.req_headers
    |> Enum.find(fn {k, _v} -> k == "referer" end)
    |> case do
      {_, v} -> URI.parse(v).path
      _ -> nil
    end
  end
end
