defmodule Web.RegistrationController do
  use Web, :controller

  alias Grapevine.Accounts
  alias Grapevine.Recaptcha
  alias GrapevineData.Games
  alias Web.SessionController

  def new(conn, _params) do
    conn
    |> assign(:changeset, Accounts.new())
    |> render("new.html")
  end

  def create(conn, params = %{"user" => user_params}) do
    case Recaptcha.valid?(params) do
      true ->
        case Accounts.register(user_params) do
          {:ok, user} ->
            conn
            |> put_session(:user_token, user.token)
            |> SessionController.after_sign_in_redirect(Routes.registration_path(conn, :finalize))

          {:error, changeset} ->
            conn
            |> put_flash(:error, "There was a problem registering. Please try again.")
            |> put_status(422)
            |> assign(:changeset, changeset)
            |> render("new.html")
        end

      false ->
        conn
        |> put_flash(:error, "There was an issue with the captcha. Please try again.")
        |> put_status(422)
        |> assign(:changeset, Accounts.new())
        |> render("new.html")
    end
  end

  def finalize(conn, _params) do
    conn
    |> assign(:games, Games.featured())
    |> assign(:show_verify_link, false)
    |> render("finalize.html")
  end
end
