defmodule MicrowavepropWeb.BeaconMonitorController do
  use MicrowavepropWeb, :controller

  alias Microwaveprop.BeaconMonitors

  def create(conn, %{"beacon_monitor" => params}) do
    user = conn.assigns.current_scope.user

    case BeaconMonitors.create_monitor(user, params) do
      {:ok, monitor} ->
        conn
        |> put_flash(:info, "Monitor '#{monitor.name}' created. Copy its token below.")
        |> redirect(to: ~p"/users/settings")

      {:error, changeset} ->
        message =
          changeset
          |> Ecto.Changeset.traverse_errors(fn {msg, _} -> msg end)
          |> Enum.map_join("; ", fn {k, v} -> "#{k}: #{Enum.join(v, ", ")}" end)

        conn
        |> put_flash(:error, "Could not create monitor (#{message}).")
        |> redirect(to: ~p"/users/settings")
    end
  end

  def delete(conn, %{"id" => id}) do
    user = conn.assigns.current_scope.user

    conn =
      case BeaconMonitors.delete_monitor(user, id) do
        {:ok, _monitor} -> put_flash(conn, :info, "Monitor deleted.")
        {:error, :not_found} -> put_flash(conn, :error, "Monitor not found.")
      end

    redirect(conn, to: ~p"/users/settings")
  end
end
