defmodule TarakanWeb.AlertLiveTest do
  use TarakanWeb.ConnCase, async: true

  import Phoenix.LiveViewTest

  alias Tarakan.Billing
  alias Tarakan.Repo

  test "redirects anonymous visitors to login", %{conn: conn} do
    assert {:error, {:redirect, %{to: "/accounts/log-in"}}} = live(conn, ~p"/alerts")
  end

  test "creates, edits, toggles, and deletes a watchlist", %{conn: conn} do
    account = account_fixture()
    {:ok, view, _html} = conn |> log_in_account(account) |> live(~p"/alerts")

    assert has_element?(view, "#watchlists")
    assert has_element?(view, "#watchlist-form")

    # Create
    view
    |> form("#watchlist-form", watchlist: %{name: "Deps", entries: "openai/codex\nacme/widget"})
    |> render_submit()

    [watchlist] = Billing.list_watchlists(account)
    assert watchlist.name == "Deps"
    assert watchlist.entries == ["openai/codex", "acme/widget"]
    assert has_element?(view, "#watchlist-#{watchlist.id}")
    assert has_element?(view, "#watchlist-#{watchlist.id}", "openai/codex")

    # Toggle notify off
    view |> element("#watchlist-notify-#{watchlist.id}") |> render_click()
    refute Repo.get!(Billing.Watchlist, watchlist.id).notify

    # Edit
    view |> element("#watchlist-edit-#{watchlist.id}") |> render_click()

    view
    |> form("#watchlist-form", watchlist: %{name: "Deps v2", entries: "openai/codex"})
    |> render_submit()

    updated = Repo.get!(Billing.Watchlist, watchlist.id)
    assert updated.name == "Deps v2"
    assert updated.entries == ["openai/codex"]
    assert has_element?(view, "#watchlist-#{watchlist.id}", "Deps v2")

    # Delete
    view |> element("#watchlist-delete-#{watchlist.id}") |> render_click()
    refute has_element?(view, "#watchlist-#{watchlist.id}")
    assert Billing.list_watchlists(account) == []
  end

  test "invalid entries show an error and do not persist", %{conn: conn} do
    account = account_fixture()
    {:ok, view, _html} = conn |> log_in_account(account) |> live(~p"/alerts")

    html =
      view
      |> form("#watchlist-form", watchlist: %{name: "Bad", entries: "not a ref"})
      |> render_submit()

    assert html =~ "owner/name"
    assert Billing.list_watchlists(account) == []
  end

  test "watchlists are owner-scoped", %{conn: conn} do
    owner = account_fixture()

    {:ok, _} =
      Billing.create_watchlist(Tarakan.Accounts.Scope.for_account(owner), %{
        "name" => "Private",
        "entries" => ["openai/codex"]
      })

    {:ok, view, _html} = conn |> log_in_account(account_fixture()) |> live(~p"/alerts")

    refute has_element?(view, "#watchlists", "Private")
  end
end
