defmodule ToweropsWeb.UserResetPasswordController do
  @moduledoc false

  use ToweropsWeb, :controller

  alias Towerops.Accounts
  alias ToweropsWeb.UserAuth

  def new(conn, _params) do
    form = Phoenix.Component.to_form(%{}, as: "user")
    render(conn, :new, form: form)
  end

  def create(conn, %{"user" => %{"email" => email}}) do
    _ =
      if user = Accounts.get_user_by_email(email) do
        Accounts.deliver_user_reset_password_instructions(
          user,
          &url(~p"/users/reset-password/#{&1}")
        )
      end

    # Always return success message to prevent email enumeration
    conn
    |> put_flash(
      :info,
      "If your email is in our system, you will receive password reset instructions shortly."
    )
    |> redirect(to: ~p"/users/log-in")
  end

  def edit(conn, %{"token" => token}) do
    case Accounts.get_user_by_reset_password_token(token) do
      nil ->
        conn
        |> put_flash(:error, "Reset password link is invalid or has expired.")
        |> redirect(to: ~p"/users/log-in")

      _user ->
        form = Phoenix.Component.to_form(%{}, as: "user")
        render(conn, :edit, form: form, token: token)
    end
  end

  def update(conn, %{"token" => token, "user" => user_params}) do
    case Accounts.get_user_by_reset_password_token(token) do
      nil ->
        conn
        |> put_flash(:error, "Reset password link is invalid or has expired.")
        |> redirect(to: ~p"/users/log-in")

      user ->
        case Accounts.reset_user_password(user, user_params) do
          {:ok, {updated_user, _expired_tokens}} ->
            conn
            |> put_flash(:info, "Password reset successfully.")
            |> UserAuth.log_in_user(updated_user, %{"remember_me" => "true"})

          {:error, changeset} ->
            form = Phoenix.Component.to_form(changeset, as: "user")
            render(conn, :edit, form: form, token: token)
        end
    end
  end
end
