defmodule MvWeb.LocaleController do
  use MvWeb, :controller

  def set_locale(conn, %{"locale" => locale}) do
    conn
    |> put_session(:locale, locale)
    # Store locale in a cookie that persists beyond the session
    |> 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

  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
