defmodule ToweropsWeb.SiteLiveTest do
  use ToweropsWeb.ConnCase, async: true

  import Phoenix.LiveViewTest

  alias Towerops.Sites

  setup :register_and_log_in_user

  setup %{conn: conn, user: user} do
    {:ok, organization} = Towerops.Organizations.create_organization(%{name: "Test Org"}, user.id)

    # Set the current organization in the session to ensure correct scope
    conn = Plug.Conn.put_session(conn, :current_organization_id, organization.id)

    %{conn: conn, organization: organization}
  end

  describe "Index" do
    test "mounts and lists sites", %{conn: conn, organization: organization} do
      {:ok, site} =
        Sites.create_site(%{name: "Main Office", organization_id: organization.id})

      {:ok, _view, html} = live(conn, ~p"/sites")

      assert html =~ "Sites"
      assert html =~ "Main Office"
      assert html =~ ~p"/sites/#{site.id}"
    end

    test "lists multiple sites", %{conn: conn, organization: organization} do
      {:ok, _} = Sites.create_site(%{name: "Site Alpha", organization_id: organization.id})
      {:ok, _} = Sites.create_site(%{name: "Site Beta", organization_id: organization.id})

      {:ok, _view, html} = live(conn, ~p"/sites")

      assert html =~ "Site Alpha"
      assert html =~ "Site Beta"
    end

    test "shows empty state when no sites", %{conn: conn} do
      {:ok, _view, html} = live(conn, ~p"/sites")

      assert html =~ "No sites"
      assert html =~ "Get started by creating your first site"
    end

    test "shows site location when present", %{conn: conn, organization: organization} do
      {:ok, _} =
        Sites.create_site(%{
          name: "Remote Office",
          location: "123 Main St",
          organization_id: organization.id
        })

      {:ok, _view, html} = live(conn, ~p"/sites")

      assert html =~ "Remote Office"
      assert html =~ "123 Main St"
    end

    test "requires authentication" do
      conn = build_conn()
      {:error, redirect} = live(conn, ~p"/sites")

      assert {:redirect, %{to: path}} = redirect
      assert path == ~p"/users/log-in"
    end
  end

  describe "Show" do
    test "mounts and displays site details", %{conn: conn, organization: organization} do
      {:ok, site} =
        Sites.create_site(%{
          name: "Headquarters",
          location: "456 Corp Ave",
          description: "Main corporate site",
          organization_id: organization.id
        })

      {:ok, _view, html} = live(conn, ~p"/sites/#{site.id}")

      assert html =~ "Headquarters"
      assert html =~ "456 Corp Ave"
      assert html =~ "Main corporate site"
      assert html =~ "Site Details"
    end

    test "lists devices at site", %{conn: conn, organization: organization} do
      {:ok, site} =
        Sites.create_site(%{name: "Data Center", organization_id: organization.id})

      {:ok, _device} =
        Towerops.Devices.create_device(%{
          name: "Core Router",
          ip_address: "10.0.0.1",
          site_id: site.id,
          organization_id: organization.id
        })

      {:ok, _view, html} = live(conn, ~p"/sites/#{site.id}")

      assert html =~ "Core Router"
      assert html =~ "10.0.0.1"
    end

    test "shows empty device state when no devices", %{conn: conn, organization: organization} do
      {:ok, site} =
        Sites.create_site(%{name: "Empty Site", organization_id: organization.id})

      {:ok, _view, html} = live(conn, ~p"/sites/#{site.id}")

      assert html =~ "Add your first device"
    end

    test "has edit link", %{conn: conn, organization: organization} do
      {:ok, site} =
        Sites.create_site(%{name: "Test Site", organization_id: organization.id})

      {:ok, view, _html} = live(conn, ~p"/sites/#{site.id}")

      assert has_element?(view, "a", "Edit")
    end

    test "requires authentication", %{organization: organization} do
      {:ok, site} =
        Sites.create_site(%{name: "Test Site", organization_id: organization.id})

      conn = build_conn()
      {:error, redirect} = live(conn, ~p"/sites/#{site.id}")

      assert {:redirect, %{to: path}} = redirect
      assert path == ~p"/users/log-in"
    end

    test "raises for site not in organization", %{conn: conn, user: user} do
      {:ok, other_org} =
        Towerops.Organizations.create_organization(%{name: "Other Org"}, user.id, bypass_limits: true)

      {:ok, other_site} =
        Sites.create_site(%{name: "Other Site", organization_id: other_org.id})

      assert_raise Ecto.NoResultsError, fn ->
        live(conn, ~p"/sites/#{other_site.id}")
      end
    end
  end

  describe "Show - Metrics Bar" do
    test "displays device count and status in metrics bar", %{
      conn: conn,
      organization: organization
    } do
      {:ok, site} =
        Sites.create_site(%{name: "Tower Alpha", organization_id: organization.id})

      {:ok, device} =
        Towerops.Devices.create_device(%{
          name: "Router",
          ip_address: "10.0.0.1",
          site_id: site.id,
          organization_id: organization.id
        })

      Towerops.Devices.update_device_status(device, :up)

      {:ok, _view, html} = live(conn, ~p"/sites/#{site.id}")

      assert html =~ "1 device"
    end

    test "displays alert count in metrics bar", %{conn: conn, organization: organization} do
      {:ok, site} =
        Sites.create_site(%{name: "Tower Beta", organization_id: organization.id})

      {:ok, device} =
        Towerops.Devices.create_device(%{
          name: "Router",
          ip_address: "10.0.0.1",
          site_id: site.id,
          organization_id: organization.id
        })

      {:ok, _alert} =
        Towerops.Alerts.create_alert(%{
          device_id: device.id,
          alert_type: :device_down,
          triggered_at: DateTime.utc_now(),
          message: "Device down"
        })

      {:ok, _view, html} = live(conn, ~p"/sites/#{site.id}")

      assert html =~ "1 alert"
    end

    test "shows subscriber badge when Gaiia network site mapped", %{
      conn: conn,
      organization: organization
    } do
      {:ok, site} =
        Sites.create_site(%{name: "Tower Gamma", organization_id: organization.id})

      {:ok, _} =
        Towerops.Devices.create_device(%{
          name: "Router",
          ip_address: "10.0.0.1",
          site_id: site.id,
          organization_id: organization.id
        })

      {:ok, _} =
        Towerops.Gaiia.upsert_network_site(organization.id, %{
          gaiia_id: "ns-gamma",
          name: "Tower Gamma",
          account_count: 75,
          total_mrr: Decimal.new("3750.00"),
          site_id: site.id
        })

      {:ok, _view, html} = live(conn, ~p"/sites/#{site.id}")

      assert html =~ "75 subscribers"
      assert html =~ "$3,750"
    end

    test "hides subscriber badge when no Gaiia mapping", %{
      conn: conn,
      organization: organization
    } do
      {:ok, site} =
        Sites.create_site(%{name: "Tower Delta", organization_id: organization.id})

      {:ok, _} =
        Towerops.Devices.create_device(%{
          name: "Router",
          ip_address: "10.0.0.1",
          site_id: site.id,
          organization_id: organization.id
        })

      {:ok, _view, html} = live(conn, ~p"/sites/#{site.id}")

      refute html =~ "subscribers"
      refute html =~ "MRR"
    end
  end

  describe "Form - New" do
    test "renders new site form", %{conn: conn} do
      {:ok, _view, html} = live(conn, ~p"/sites/new")

      assert html =~ "New Site"
      assert html =~ "Add a new site to your organization"
      assert html =~ "Site Name"
      assert html =~ "Save Site"
    end

    test "validates site name is required", %{conn: conn} do
      {:ok, view, _html} = live(conn, ~p"/sites/new")

      html =
        view
        |> form("#site-form", site: %{name: ""})
        |> render_change()

      assert html =~ "can&#39;t be blank"
    end

    test "validates site name minimum length", %{conn: conn} do
      {:ok, view, _html} = live(conn, ~p"/sites/new")

      html =
        view
        |> form("#site-form", site: %{name: "X"})
        |> render_change()

      assert html =~ "should be at least 2 character(s)"
    end

    test "creates site and redirects to show page", %{conn: conn} do
      {:ok, view, _html} = live(conn, ~p"/sites/new")

      view
      |> form("#site-form", site: %{name: "New Branch Office"})
      |> render_submit()

      {path, flash} = assert_redirect(view)
      assert path =~ ~r|^/sites/.+|
      assert flash["info"] =~ "Site created successfully"
    end

    test "creates site with optional fields", %{conn: conn, organization: organization} do
      {:ok, view, _html} = live(conn, ~p"/sites/new")

      view
      |> form("#site-form",
        site: %{
          name: "Full Details Site",
          location: "789 Elm St",
          description: "A well-documented site"
        }
      )
      |> render_submit()

      assert_redirect(view)

      sites = Sites.list_organization_sites(organization.id)
      site = Enum.find(sites, &(&1.name == "Full Details Site"))
      assert site
      assert site.location == "789 Elm St"
    end

    test "shows validation error for duplicate name", %{conn: conn, organization: organization} do
      {:ok, _} = Sites.create_site(%{name: "Existing Site", organization_id: organization.id})

      {:ok, view, _html} = live(conn, ~p"/sites/new")

      html =
        view
        |> form("#site-form", site: %{name: "Existing Site"})
        |> render_submit()

      assert html =~ "has already been taken for this organization"
    end

    test "has back link to sites list", %{conn: conn} do
      {:ok, _view, html} = live(conn, ~p"/sites/new")

      assert html =~ "Back to Sites"
      assert html =~ ~p"/sites"
    end

    test "requires authentication" do
      conn = build_conn()
      {:error, redirect} = live(conn, ~p"/sites/new")

      assert {:redirect, %{to: path}} = redirect
      assert path == ~p"/users/log-in"
    end
  end

  describe "Form - Edit" do
    test "loads existing site into form", %{conn: conn, organization: organization} do
      {:ok, site} =
        Sites.create_site(%{
          name: "Original Name",
          location: "Original Location",
          organization_id: organization.id
        })

      {:ok, _view, html} = live(conn, ~p"/sites/#{site.id}/edit")

      assert html =~ "Edit Site"
      assert html =~ "Update site details"
      assert html =~ "Original Name"
      assert html =~ "Original Location"
    end

    test "validates on change", %{conn: conn, organization: organization} do
      {:ok, site} =
        Sites.create_site(%{name: "Test Site", organization_id: organization.id})

      {:ok, view, _html} = live(conn, ~p"/sites/#{site.id}/edit")

      html =
        view
        |> form("#site-form", site: %{name: ""})
        |> render_change()

      assert html =~ "can&#39;t be blank"
    end

    test "saves changes and redirects", %{conn: conn, organization: organization} do
      {:ok, site} =
        Sites.create_site(%{name: "Old Name", organization_id: organization.id})

      {:ok, view, _html} = live(conn, ~p"/sites/#{site.id}/edit")

      view
      |> form("#site-form", site: %{name: "Updated Name"})
      |> render_submit()

      {path, _flash} = assert_redirect(view)
      assert path == ~p"/sites"

      updated_site = Sites.get_organization_site!(organization.id, site.id)
      assert updated_site.name == "Updated Name"
    end

    test "has back link to site show page", %{conn: conn, organization: organization} do
      {:ok, site} =
        Sites.create_site(%{name: "Test Site", organization_id: organization.id})

      {:ok, _view, html} = live(conn, ~p"/sites/#{site.id}/edit")

      assert html =~ "Back to Site"
      assert html =~ ~p"/sites/#{site.id}"
    end

    test "requires authentication", %{organization: organization} do
      {:ok, site} =
        Sites.create_site(%{name: "Test Site", organization_id: organization.id})

      conn = build_conn()
      {:error, redirect} = live(conn, ~p"/sites/#{site.id}/edit")

      assert {:redirect, %{to: path}} = redirect
      assert path == ~p"/users/log-in"
    end

    test "raises for site not in organization", %{conn: conn, user: user} do
      {:ok, other_org} =
        Towerops.Organizations.create_organization(%{name: "Other Org"}, user.id, bypass_limits: true)

      {:ok, other_site} =
        Sites.create_site(%{name: "Other Site", organization_id: other_org.id})

      assert_raise Ecto.NoResultsError, fn ->
        live(conn, ~p"/sites/#{other_site.id}/edit")
      end
    end
  end

  describe "Form - Delete" do
    test "deletes site and redirects to index", %{conn: conn, organization: organization} do
      {:ok, site} =
        Sites.create_site(%{name: "Doomed Site", organization_id: organization.id})

      {:ok, view, _html} = live(conn, ~p"/sites/#{site.id}/edit")

      view
      |> element("button", "Delete Site")
      |> render_click()

      {path, _flash} = assert_redirect(view)
      assert path == ~p"/sites"

      assert_raise Ecto.NoResultsError, fn ->
        Sites.get_organization_site!(organization.id, site.id)
      end
    end

    test "delete button only appears on edit page", %{conn: conn, organization: organization} do
      {:ok, site} =
        Sites.create_site(%{name: "Test Site", organization_id: organization.id})

      # Edit page should have delete
      {:ok, edit_view, _html} = live(conn, ~p"/sites/#{site.id}/edit")
      assert has_element?(edit_view, "button", "Delete Site")

      # New page should not have delete
      {:ok, new_view, _html} = live(conn, ~p"/sites/new")
      refute has_element?(new_view, "button", "Delete Site")
    end
  end
end
