defmodule MicrowavepropWeb.BeaconMonitorControllerTest do
  use MicrowavepropWeb.ConnCase, async: true

  import Microwaveprop.AccountsFixtures

  alias Microwaveprop.BeaconMonitors

  setup :register_and_log_in_user

  describe "POST /users/beacon-monitors" do
    test "creates a monitor for the current user", %{conn: conn, user: user} do
      conn =
        post(conn, ~p"/users/beacon-monitors", %{
          "beacon_monitor" => %{"name" => "Shack Pi"}
        })

      assert redirected_to(conn) == ~p"/users/settings"
      assert Phoenix.Flash.get(conn.assigns.flash, :info) =~ "Shack Pi"

      assert [monitor] = BeaconMonitors.list_monitors_for_user(user)
      assert monitor.name == "Shack Pi"
      assert is_binary(monitor.token)
    end

    test "shows an error when name is blank", %{conn: conn, user: user} do
      conn =
        post(conn, ~p"/users/beacon-monitors", %{
          "beacon_monitor" => %{"name" => ""}
        })

      assert redirected_to(conn) == ~p"/users/settings"
      assert Phoenix.Flash.get(conn.assigns.flash, :error) =~ "name"
      assert BeaconMonitors.list_monitors_for_user(user) == []
    end

    test "redirects unauthenticated users to login" do
      conn = post(build_conn(), ~p"/users/beacon-monitors", %{"beacon_monitor" => %{"name" => "Nope"}})

      assert redirected_to(conn) == ~p"/users/log-in"
    end
  end

  describe "DELETE /users/beacon-monitors/:id" do
    test "deletes a monitor owned by the current user", %{conn: conn, user: user} do
      {:ok, monitor} = BeaconMonitors.create_monitor(user, %{"name" => "Bye"})

      conn = delete(conn, ~p"/users/beacon-monitors/#{monitor.id}")

      assert redirected_to(conn) == ~p"/users/settings"
      assert Phoenix.Flash.get(conn.assigns.flash, :info) =~ "deleted"
      assert BeaconMonitors.list_monitors_for_user(user) == []
    end

    test "does not delete a monitor owned by another user", %{conn: conn} do
      other = user_fixture()
      {:ok, monitor} = BeaconMonitors.create_monitor(other, %{"name" => "Theirs"})

      conn = delete(conn, ~p"/users/beacon-monitors/#{monitor.id}")

      assert redirected_to(conn) == ~p"/users/settings"
      assert Phoenix.Flash.get(conn.assigns.flash, :error) =~ "not found"
      assert [_] = BeaconMonitors.list_monitors_for_user(other)
    end
  end
end
