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.Radio.ContactEdit
  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

  describe "review flow" do
    # Walks a pending edit through review → approve (and review → reject)
    # via LiveView events. Each path hits one of the main approve/reject
    # branches in the LiveView plus the helper label/value renderers.

    defp seed_pending_edit do
      admin = admin_fixture()
      submitter = user_fixture()
      contact = create_contact(%{station1: "N5XXX"})

      {:ok, edit} =
        Microwaveprop.Radio.create_contact_edit(contact, submitter, %{
          "station1" => "N5YYY",
          "mode" => "SSB",
          "band" => "432",
          "grid1" => "EM13",
          "qso_timestamp" => "2026-04-01 12:00:00Z"
        })

      {admin, contact, edit}
    end

    test "clicking Review opens the edit inspector with current + proposed values", %{conn: conn} do
      {admin, contact, edit} = seed_pending_edit()

      {:ok, lv, _html} =
        conn
        |> log_in_user(admin)
        |> live(~p"/admin/contact-edits")

      html =
        lv
        |> element(~s|button[phx-click="review"][phx-value-id="#{edit.id}"]|)
        |> render_click()

      # Inspector panel shows labels for every field that changed.
      assert html =~ "Station 1"
      assert html =~ "Mode"
      assert html =~ "Band"
      assert html =~ "Grid 1"
      assert html =~ "Timestamp"

      # Current values from the contact row.
      assert html =~ contact.station1
      # Proposed values from the edit.
      assert html =~ "N5YYY"
      assert html =~ "SSB"
    end

    test "approve applies the edit and clears the inspector", %{conn: conn} do
      {admin, _contact, edit} = seed_pending_edit()

      {:ok, lv, _html} =
        conn
        |> log_in_user(admin)
        |> live(~p"/admin/contact-edits")

      lv
      |> element(~s|button[phx-click="review"][phx-value-id="#{edit.id}"]|)
      |> render_click()

      html =
        lv
        |> element(~s|button[phx-click="approve"]|)
        |> render_click()

      # Flash + pending counter refresh.
      assert html =~ "Edit approved and applied"
      assert html =~ "0 pending"

      # The edit now holds the admin's stamp in the DB.
      approved = Repo.get!(ContactEdit, edit.id)
      assert approved.status == :approved
      assert approved.reviewed_by_id == admin.id
    end

    test "reject leaves the contact unchanged and records the rejection", %{conn: conn} do
      {admin, contact, edit} = seed_pending_edit()

      {:ok, lv, _html} =
        conn
        |> log_in_user(admin)
        |> live(~p"/admin/contact-edits")

      lv
      |> element(~s|button[phx-click="review"][phx-value-id="#{edit.id}"]|)
      |> render_click()

      # Type an admin note into the review textarea first. It's not
      # wrapped in a <form>, so hit the element directly.
      lv
      |> element(~s|textarea[phx-change="update_note"]|)
      |> render_change(%{note: "  not enough context  "})

      html =
        lv
        |> element(~s|button[phx-click="reject"]|)
        |> render_click()

      assert html =~ "Edit rejected"

      rejected = Repo.get!(ContactEdit, edit.id)
      assert rejected.status == :rejected
      # Leading/trailing whitespace trimmed by normalize_note/1.
      assert rejected.admin_note == "not enough context"

      # The contact was NOT mutated — station1 stays as it was.
      assert Repo.get!(Contact, contact.id).station1 == contact.station1
    end

    test "cancel_review clears the inspector without touching the edit", %{conn: conn} do
      {admin, _contact, edit} = seed_pending_edit()

      {:ok, lv, _html} =
        conn
        |> log_in_user(admin)
        |> live(~p"/admin/contact-edits")

      # Open the inspector.
      lv
      |> element(~s|button[phx-click="review"][phx-value-id="#{edit.id}"]|)
      |> render_click()

      html =
        lv
        |> element(~s|button[phx-click="cancel_review"]|)
        |> render_click()

      # Inspector is closed — specific proposed-value column no longer shows.
      refute html =~ "Proposed"
      # And the edit is still pending in the DB.
      assert Repo.get!(ContactEdit, edit.id).status == :pending
    end
  end
end
