defmodule MicrowavepropWeb.UserSessionController do
  use MicrowavepropWeb, :controller

  alias Microwaveprop.Accounts
  alias Microwaveprop.Accounts.User
  alias MicrowavepropWeb.UserAuth

  def new(conn, _params) do
    email = get_in(conn.assigns, [:current_scope, Access.key(:user), Access.key(:email)])
    form = Phoenix.Component.to_form(%{"email" => email}, as: "user")

    render(conn, :new, form: form)
  end

  def create(conn, %{"user" => %{"email" => email, "password" => password} = user_params}) do
    case Accounts.get_user_by_email_and_password(email, password) do
      %User{confirmed_at: nil} ->
        form = Phoenix.Component.to_form(user_params, as: "user")

        conn
        |> put_flash(
          :error,
          "Please confirm your email address before logging in. Check your inbox for the confirmation link."
        )
        |> render(:new, form: form)

      %User{} = user ->
        conn
        |> put_flash(:info, "Welcome back!")
        |> UserAuth.log_in_user(user, user_params)

      nil ->
        form = Phoenix.Component.to_form(user_params, as: "user")

        # In order to prevent user enumeration attacks, don't disclose whether the email is registered.
        conn
        |> put_flash(:error, "Invalid email or password")
        |> render(:new, form: form)
    end
  end

  def confirm(conn, %{"token" => token}) do
    case Accounts.confirm_user_by_token(token) do
      {:ok, {user, _expired_tokens}} ->
        conn
        |> put_flash(:info, "Account confirmed. Welcome!")
        |> UserAuth.log_in_user(user)

      {:error, _reason} ->
        conn
        |> put_flash(:error, "Confirmation link is invalid or has expired.")
        |> redirect(to: ~p"/users/log-in")
    end
  end

  def delete(conn, _params) do
    conn
    |> put_flash(:info, "Logged out successfully.")
    |> UserAuth.log_out_user()
  end
end
