defmodule Mix.Tasks.Aprsme.UserRole do
  @shortdoc "Promotes or demotes an existing user"
  @moduledoc """
  Sets an existing user's role by email.

      mix aprsme.user_role user@example.com admin
      mix aprsme.user_role user@example.com user
  """

  use Mix.Task

  @impl Mix.Task
  def run([email, role_name]) when role_name in ["user", "admin"] do
    Mix.Task.run("app.start")

    case Aprsme.Accounts.get_user_by_email(email) do
      nil ->
        Mix.raise("No user found with email #{email}")

      user ->
        role = String.to_existing_atom(role_name)

        case Aprsme.Accounts.set_user_role(user, role) do
          {:ok, _user} -> Mix.shell().info("Set #{email} role to #{role_name}")
          {:error, changeset} -> Mix.raise("Could not update role: #{inspect(changeset.errors)}")
        end
    end
  end

  def run(_args), do: Mix.raise("Usage: mix aprsme.user_role EMAIL user|admin")
end
