defmodule Overbooked.Accounts do
  @moduledoc """
  The Accounts context.
  """

  import Ecto.Query, warn: false
  alias Overbooked.Repo

  alias Overbooked.Accounts.{RegistrationToken, User, UserToken, UserNotifier}

  ## Database getters

  def list_users(opts \\ []) do
    from(u in User,
      limit: ^Keyword.get(opts, :limit, 100)
    )
    |> Repo.all()
  end

  def list_invitations(opts \\ []) do
    from(r in RegistrationToken,
      limit: ^Keyword.get(opts, :limit, 100),
      preload: [:generated_by_user, :used_by_user]
    )
    |> Repo.all()
  end

  @doc """
  Gets a user by email.

  ## Examples

      iex> get_user_by_email("foo@example.com")
      %User{}

      iex> get_user_by_email("unknown@example.com")
      nil

  """
  def get_user_by_email(email) when is_binary(email) do
    Repo.get_by(User, email: email)
  end

  @doc """
  Gets a user by email and password.

  ## Examples

      iex> get_user_by_email_and_password("foo@example.com", "correct_password")
      %User{}

      iex> get_user_by_email_and_password("foo@example.com", "invalid_password")
      nil

  """
  def get_user_by_email_and_password(email, password)
      when is_binary(email) and is_binary(password) do
    user = Repo.get_by(User, email: email)
    if User.valid_password?(user, password), do: user
  end

  @doc """
  Gets a single user.

  Raises `Ecto.NoResultsError` if the User does not exist.

  ## Examples

      iex> get_user!(123)
      %User{}

      iex> get_user!(456)
      ** (Ecto.NoResultsError)

  """
  def get_user!(id), do: Repo.get!(User, id)

  def delete_user(deleted_by_user, user) do
    if !User.is_admin?(deleted_by_user) do
      {:error, :forbidden}
    else
      Repo.delete(user)
    end
  end

  def update_admin(action_by_user, user, attr) do
    if !User.is_admin?(action_by_user) do
      {:error, :forbidden}
    else
      user
      |> User.admin_changeset(attr)
      |> Repo.update()
    end
  end

  ## User registration

  def get_registration_token!(id), do: Repo.get!(RegistrationToken, id)

  def delete_registration_token(deleted_by_user, registration_token) do
    if !User.is_admin?(deleted_by_user) do
      {:error, :forbidden}
    else
      Repo.delete(registration_token)
    end
  end

  def generate_registration_token(opts \\ []) do
    {token_string, hashed_token} = RegistrationToken.build_hashed_token()

    %{
      token: hashed_token,
      token_string: token_string,
      generated_by_user_id: Keyword.get(opts, :generated_by),
      scoped_to_email: Keyword.get(opts, :scoped_to_email)
    }
    |> RegistrationToken.create_changeset()
    |> Repo.insert()
  end

  def register_user_with_token(token_string, attrs) do
    token_string
    |> maybe_get_registration_token()
    |> maybe_register_user_with_token(attrs)
  end

  def deliver_user_invitation_instructions(
        %User{} = generated_by_user,
        invitation_email,
        registration_url_fun
      )
      when is_function(registration_url_fun, 1) do
    if !User.is_admin?(generated_by_user) do
      {:error, :forbidden}
    else
      {:ok, %RegistrationToken{} = token} =
        generate_registration_token(
          generated_by: generated_by_user.id,
          scoped_to_email: invitation_email
        )

      UserNotifier.deliver_user_invitation_instructions(
        invitation_email,
        registration_url_fun.(token.token_string)
      )
    end
  end

  @hash_algorithm :sha256
  defp maybe_get_registration_token(token) when is_binary(token) do
    Base.url_decode64(token, padding: false)
    |> case do
      {:ok, decoded_token} ->
        hashed_token = :crypto.hash(@hash_algorithm, decoded_token)

        RegistrationToken.get_registration_token_query(hashed_token)
        |> Repo.one()

      :error ->
        nil
    end
  end

  defp maybe_get_registration_token(_), do: nil

  # token was not found
  defp maybe_register_user_with_token(nil, attrs) do
    invalid_token_response(attrs)
  end

  # non-email scoped token
  defp maybe_register_user_with_token(%RegistrationToken{scoped_to_email: nil} = token, attrs) do
    Repo.transaction(fn ->
      with {:ok, user} <- register_user(attrs),
           {:ok, _registration_token} <- consume_registration_token(token, user) do
        user
      else
        {:error, error} ->
          Repo.rollback(error)
      end
    end)
  end

  # email scoped token
  defp maybe_register_user_with_token(token, attrs) do
    if token.scoped_to_email == (attrs["email"] || attrs[:email]) do
      Repo.transaction(fn ->
        with {:ok, user} <- register_user(attrs),
             {:ok, _registration_token} <- consume_registration_token(token, user) do
          user
        else
          {:error, error} ->
            Repo.rollback(error)
        end
      end)

      # wrong email scope
    else
      invalid_token_response(attrs)
    end
  end

  defp invalid_token_response(attrs) do
    %User{}
    |> User.registration_changeset(attrs)
    |> Ecto.Changeset.add_error(:registration_token, "Invalid registration token!")
    |> Ecto.Changeset.apply_action(:update)
  end

  defp consume_registration_token(token, user) do
    RegistrationToken.consume_token_changeset(token, user.id)
    |> Repo.update()
  end

  defp register_user(attrs) do
    %User{}
    |> User.registration_changeset(attrs)
    |> Repo.insert()
  end

  @doc """
  Returns an `%Ecto.Changeset{}` for tracking user changes.

  ## Examples

      iex> change_user_registration(user)
      %Ecto.Changeset{data: %User{}}

  """
  def change_user_registration(%User{} = user, attrs \\ %{}) do
    User.registration_changeset(user, attrs, hash_password: false)
  end

  ## Settings

  @doc """
  Returns an `%Ecto.Changeset{}` for changing the user email.

  ## Examples

      iex> change_user_email(user)
      %Ecto.Changeset{data: %User{}}

  """
  def change_user_email(user, attrs \\ %{}) do
    User.email_changeset(user, attrs)
  end

  def update_user_profile(user, attrs \\ %{}) do
    user
    |> User.profile_changeset(attrs)
    |> Repo.update()
  end

  def change_user_profile(user, attrs \\ %{}) do
    User.profile_changeset(user, attrs)
  end

  @doc """
  Emulates that the email will change without actually changing
  it in the database.

  ## Examples

      iex> apply_user_email(user, "valid password", %{email: ...})
      {:ok, %User{}}

      iex> apply_user_email(user, "invalid password", %{email: ...})
      {:error, %Ecto.Changeset{}}

  """
  def apply_user_email(user, password, attrs) do
    user
    |> User.email_changeset(attrs)
    |> User.validate_current_password(password)
    |> Ecto.Changeset.apply_action(:update)
  end

  @doc """
  Updates the user email using the given token.

  If the token matches, the user email is updated and the token is deleted.
  The confirmed_at date is also updated to the current time.
  """
  def update_user_email(user, token) do
    context = "change:#{user.email}"

    with {:ok, query} <- UserToken.verify_change_email_token_query(token, context),
         %UserToken{sent_to: email} <- Repo.one(query),
         {:ok, _} <- Repo.transaction(user_email_multi(user, email, context)) do
      :ok
    else
      _ -> :error
    end
  end

  defp user_email_multi(user, email, context) do
    changeset =
      user
      |> User.email_changeset(%{email: email})
      |> User.confirm_changeset()

    Ecto.Multi.new()
    |> Ecto.Multi.update(:user, changeset)
    |> Ecto.Multi.delete_all(:tokens, UserToken.user_and_contexts_query(user, [context]))
  end

  @doc """
  Delivers the update email instructions to the given user.

  ## Examples

      iex> deliver_update_email_instructions(user, current_email, &Routes.user_update_email_url(conn, :edit, &1))
      {:ok, %{to: ..., body: ...}}

  """
  def deliver_update_email_instructions(%User{} = user, current_email, update_email_url_fun)
      when is_function(update_email_url_fun, 1) do
    {encoded_token, user_token} = UserToken.build_email_token(user, "change:#{current_email}")

    Repo.insert!(user_token)
    UserNotifier.deliver_update_email_instructions(user, update_email_url_fun.(encoded_token))
  end

  @doc """
  Returns an `%Ecto.Changeset{}` for changing the user password.

  ## Examples

      iex> change_user_password(user)
      %Ecto.Changeset{data: %User{}}

  """
  def change_user_password(user, attrs \\ %{}) do
    User.password_changeset(user, attrs, hash_password: false)
  end

  @doc """
  Updates the user password.

  ## Examples

      iex> update_user_password(user, "valid password", %{password: ...})
      {:ok, %User{}}

      iex> update_user_password(user, "invalid password", %{password: ...})
      {:error, %Ecto.Changeset{}}

  """
  def update_user_password(user, password, attrs) do
    changeset =
      user
      |> User.password_changeset(attrs)
      |> User.validate_current_password(password)

    Ecto.Multi.new()
    |> Ecto.Multi.update(:user, changeset)
    |> Ecto.Multi.delete_all(:tokens, UserToken.user_and_contexts_query(user, :all))
    |> Repo.transaction()
    |> case do
      {:ok, %{user: user}} -> {:ok, user}
      {:error, :user, changeset, _} -> {:error, changeset}
    end
  end

  ## Session

  @doc """
  Generates a session token.
  """
  def generate_user_session_token(user) do
    {token, user_token} = UserToken.build_session_token(user)
    Repo.insert!(user_token)
    token
  end

  @doc """
  Gets the user with the given signed token.
  """
  def get_user_by_session_token(token) do
    {:ok, query} = UserToken.verify_session_token_query(token)
    Repo.one(query)
  end

  @doc """
  Deletes the signed token with the given context.
  """
  def delete_session_token(token) do
    Repo.delete_all(UserToken.token_and_context_query(token, "session"))
    :ok
  end

  ## Confirmation

  @doc """
  Delivers the confirmation email instructions to the given user.

  ## Examples

      iex> deliver_user_confirmation_instructions(user, &Routes.user_confirmation_url(conn, :edit, &1))
      {:ok, %{to: ..., body: ...}}

      iex> deliver_user_confirmation_instructions(confirmed_user, &Routes.user_confirmation_url(conn, :edit, &1))
      {:error, :already_confirmed}

  """
  def deliver_user_confirmation_instructions(%User{} = user, confirmation_url_fun)
      when is_function(confirmation_url_fun, 1) do
    if user.confirmed_at do
      {:error, :already_confirmed}
    else
      {encoded_token, user_token} = UserToken.build_email_token(user, "confirm")
      Repo.insert!(user_token)
      UserNotifier.deliver_confirmation_instructions(user, confirmation_url_fun.(encoded_token))
    end
  end

  @doc """
  Confirms a user by the given token.

  If the token matches, the user account is marked as confirmed
  and the token is deleted.
  """
  def confirm_user(token) do
    with {:ok, query} <- UserToken.verify_email_token_query(token, "confirm"),
         %User{} = user <- Repo.one(query),
         {:ok, %{user: user}} <- Repo.transaction(confirm_user_multi(user)) do
      {:ok, user}
    else
      _ -> :error
    end
  end

  defp confirm_user_multi(user) do
    Ecto.Multi.new()
    |> Ecto.Multi.update(:user, User.confirm_changeset(user))
    |> Ecto.Multi.delete_all(:tokens, UserToken.user_and_contexts_query(user, ["confirm"]))
  end

  ## Reset password

  @doc """
  Delivers the reset password email to the given user.

  ## Examples

      iex> deliver_user_reset_password_instructions(user, &Routes.user_reset_password_url(conn, :edit, &1))
      {:ok, %{to: ..., body: ...}}

  """
  def deliver_user_reset_password_instructions(%User{} = user, reset_password_url_fun)
      when is_function(reset_password_url_fun, 1) do
    {encoded_token, user_token} = UserToken.build_email_token(user, "reset_password")
    Repo.insert!(user_token)
    UserNotifier.deliver_reset_password_instructions(user, reset_password_url_fun.(encoded_token))
  end

  @doc """
  Gets the user by reset password token.

  ## Examples

      iex> get_user_by_reset_password_token("validtoken")
      %User{}

      iex> get_user_by_reset_password_token("invalidtoken")
      nil

  """
  def get_user_by_reset_password_token(token) do
    with {:ok, query} <- UserToken.verify_email_token_query(token, "reset_password"),
         %User{} = user <- Repo.one(query) do
      user
    else
      _ -> nil
    end
  end

  @doc """
  Resets the user password.

  ## Examples

      iex> reset_user_password(user, %{password: "new long password", password_confirmation: "new long password"})
      {:ok, %User{}}

      iex> reset_user_password(user, %{password: "valid", password_confirmation: "not the same"})
      {:error, %Ecto.Changeset{}}

  """
  def reset_user_password(user, attrs) do
    Ecto.Multi.new()
    |> Ecto.Multi.update(:user, User.password_changeset(user, attrs))
    |> Ecto.Multi.delete_all(:tokens, UserToken.user_and_contexts_query(user, :all))
    |> Repo.transaction()
    |> case do
      {:ok, %{user: user}} -> {:ok, user}
      {:error, :user, changeset, _} -> {:error, changeset}
    end
  end
end
