defmodule MicrowavepropWeb.Admin.ContactEditLiveTest do
  use MicrowavepropWeb.ConnCase, async: false

  import Microwaveprop.AccountsFixtures
  import Phoenix.LiveViewTest

  alias Microwaveprop.Accounts
  alias Microwaveprop.Radio.Contact
  alias Microwaveprop.Repo

  defp admin_fixture do
    user = user_fixture()
    {:ok, user} = Accounts.admin_update_user(user, %{is_admin: true})
    user
  end

  defp create_contact(attrs \\ %{}) do
    default = %{
      station1: "W5XD",
      station2: "K5TR",
      qso_timestamp: ~U[2026-03-28 18:00:00Z],
      mode: "CW",
      band: Decimal.new("1296"),
      grid1: "EM12",
      grid2: "EM00",
      pos1: %{"lat" => 32.9, "lon" => -97.0},
      pos2: %{"lat" => 30.3, "lon" => -97.7},
      distance_km: Decimal.new("295")
    }

    merged = Map.merge(default, attrs)
    # `flagged_invalid` isn't a user-facing submission field, so the
    # changeset's cast drops it. Set it directly via change/2.
    {direct_attrs, castable} = Map.split(merged, [:flagged_invalid])

    {:ok, contact} =
      %Contact{}
      |> Contact.changeset(castable)
      |> Ecto.Changeset.change(direct_attrs)
      |> Repo.insert()

    contact
  end

  describe "flagged contacts section" do
    test "hidden when no contacts are flagged", %{conn: conn} do
      _ok = create_contact(%{station1: "W5OK"})
      conn = log_in_user(conn, admin_fixture())

      {:ok, _lv, html} = live(conn, ~p"/admin/contact-edits")
      refute html =~ "Flagged contacts"
    end

    test "lists flagged contacts with station callsigns for admins", %{conn: conn} do
      _ok = create_contact(%{station1: "W5OK"})
      _flagged = create_contact(%{station1: "W5BAD", flagged_invalid: true})
      conn = log_in_user(conn, admin_fixture())

      {:ok, _lv, html} = live(conn, ~p"/admin/contact-edits")
      assert html =~ "Flagged contacts"
      assert html =~ "W5BAD"
    end

    test "does not leak flagged contacts into the pending-edits table", %{conn: conn} do
      _flagged = create_contact(%{station1: "W5BAD", flagged_invalid: true})
      conn = log_in_user(conn, admin_fixture())

      {:ok, _lv, html} = live(conn, ~p"/admin/contact-edits")
      # The flagged list mentions W5BAD, but only inside the flagged
      # section — the pending-edits table above should stay empty.
      assert html =~ "0 pending"
    end
  end
end
