defmodule FirehoseWeb.UserRegistrationController do
  use FirehoseWeb, :controller

  alias Firehose.Accounts
  alias Firehose.Accounts.User

  def new(conn, _params) do
    changeset = Accounts.change_user_email(%User{})
    render(conn, :new, changeset: changeset)
  end

  def create(conn, %{"user" => user_params}) do
    allowed_email = Application.get_env(:firehose, :allowed_registration_email)

    if allowed_email == nil or user_params["email"] != allowed_email do
      changeset =
        %User{}
        |> Accounts.change_user_email(user_params)
        |> Ecto.Changeset.add_error(:email, "registration is invite only.")
        |> Map.put(:action, :validate)

      render(conn, :new, changeset: changeset)
    else
      case Accounts.register_user(user_params) do
        {:ok, user} ->
          {:ok, _} =
            Accounts.deliver_login_instructions(
              user,
              &url(~p"/users/log-in/#{&1}")
            )

          conn
          |> put_flash(
            :info,
            "An email was sent to #{user.email}, please access it to confirm your account."
          )
          |> redirect(to: ~p"/users/log-in")

        {:error, %Ecto.Changeset{} = changeset} ->
          render(conn, :new, changeset: changeset)
      end
    end
  end
end
