defmodule ToweropsWeb.Org.IntegrationsLiveTest do
  use ToweropsWeb.ConnCase

  import Phoenix.LiveViewTest
  import Towerops.AccountsFixtures
  import Towerops.OrganizationsFixtures

  alias Towerops.Preseem.Client, as: PreseemClient

  setup do
    user = user_fixture()
    organization = organization_fixture(user.id)
    %{user: user, organization: organization}
  end

  describe "gaiia webhook setup" do
    test "saving a new gaiia integration auto-generates a webhook secret", %{
      conn: conn,
      user: user,
      organization: org
    } do
      {:ok, view, _html} =
        conn
        |> log_in_user(user)
        |> live(~p"/orgs/#{org.slug}/settings/integrations")

      view |> element("#configure-gaiia") |> render_click()

      view
      |> form("#gaiia-form", %{integration: %{api_key: "test-gaiia-key"}})
      |> render_submit()

      assert {:ok, integration} = Towerops.Integrations.get_integration(org.id, "gaiia")
      assert integration.credentials["api_key"] == "test-gaiia-key"
      assert integration.credentials["webhook_secret"]
      assert String.length(integration.credentials["webhook_secret"]) == 64
    end

    test "saving an existing gaiia integration preserves the webhook secret", %{
      conn: conn,
      user: user,
      organization: org
    } do
      # Create integration with a known webhook secret
      {:ok, _integration} =
        Towerops.Integrations.create_integration(org.id, %{
          provider: "gaiia",
          enabled: true,
          credentials: %{"api_key" => "old-key", "webhook_secret" => "existing-secret-abc"}
        })

      {:ok, view, _html} =
        conn
        |> log_in_user(user)
        |> live(~p"/orgs/#{org.slug}/settings/integrations")

      view |> element("#configure-gaiia") |> render_click()

      view
      |> form("#gaiia-form", %{integration: %{api_key: "new-gaiia-key"}})
      |> render_submit()

      assert {:ok, integration} = Towerops.Integrations.get_integration(org.id, "gaiia")
      assert integration.credentials["api_key"] == "new-gaiia-key"
      assert integration.credentials["webhook_secret"] == "existing-secret-abc"
    end

    test "displays webhook URL when gaiia integration exists", %{
      conn: conn,
      user: user,
      organization: org
    } do
      {:ok, _integration} =
        Towerops.Integrations.create_integration(org.id, %{
          provider: "gaiia",
          enabled: true,
          credentials: %{"api_key" => "key", "webhook_secret" => "secret123"}
        })

      {:ok, _view, html} =
        conn
        |> log_in_user(user)
        |> live(~p"/orgs/#{org.slug}/settings/integrations")

      assert html =~ "/api/v1/webhooks/gaiia/#{org.id}"
    end

    test "displays webhook secret when gaiia integration exists", %{
      conn: conn,
      user: user,
      organization: org
    } do
      {:ok, _integration} =
        Towerops.Integrations.create_integration(org.id, %{
          provider: "gaiia",
          enabled: true,
          credentials: %{"api_key" => "key", "webhook_secret" => "secret123"}
        })

      {:ok, _view, html} =
        conn
        |> log_in_user(user)
        |> live(~p"/orgs/#{org.slug}/settings/integrations")

      assert html =~ "secret123"
    end

    test "regenerate webhook secret changes the stored secret", %{
      conn: conn,
      user: user,
      organization: org
    } do
      {:ok, _integration} =
        Towerops.Integrations.create_integration(org.id, %{
          provider: "gaiia",
          enabled: true,
          credentials: %{"api_key" => "key", "webhook_secret" => "old-secret"}
        })

      {:ok, view, _html} =
        conn
        |> log_in_user(user)
        |> live(~p"/orgs/#{org.slug}/settings/integrations")

      view |> element("#regenerate-webhook-secret") |> render_click()

      assert {:ok, integration} = Towerops.Integrations.get_integration(org.id, "gaiia")
      assert integration.credentials["webhook_secret"] != "old-secret"
      assert String.length(integration.credentials["webhook_secret"]) == 64
      assert integration.credentials["api_key"] == "key"
    end

    test "shows setup instructions when gaiia integration exists", %{
      conn: conn,
      user: user,
      organization: org
    } do
      {:ok, _integration} =
        Towerops.Integrations.create_integration(org.id, %{
          provider: "gaiia",
          enabled: true,
          credentials: %{"api_key" => "key", "webhook_secret" => "secret"}
        })

      {:ok, _view, html} =
        conn
        |> log_in_user(user)
        |> live(~p"/orgs/#{org.slug}/settings/integrations")

      assert html =~ "Webhook Configuration"
      assert html =~ "Webhook URL"
      assert html =~ "Webhook Secret"
      assert html =~ "Gaiia admin panel"
    end
  end

  describe "index" do
    test "renders integrations page", %{conn: conn, user: user, organization: org} do
      {:ok, _view, html} =
        conn
        |> log_in_user(user)
        |> live(~p"/orgs/#{org.slug}/settings/integrations")

      assert html =~ "Integrations"
      assert html =~ "Preseem"
    end

    test "shows preseem description", %{conn: conn, user: user, organization: org} do
      {:ok, _view, html} =
        conn
        |> log_in_user(user)
        |> live(~p"/orgs/#{org.slug}/settings/integrations")

      assert html =~ "QoE monitoring"
    end

    test "can open preseem configuration", %{conn: conn, user: user, organization: org} do
      {:ok, view, _html} =
        conn
        |> log_in_user(user)
        |> live(~p"/orgs/#{org.slug}/settings/integrations")

      html = view |> element("#configure-preseem") |> render_click()
      assert html =~ "API Key"
    end

    test "can save preseem credentials", %{conn: conn, user: user, organization: org} do
      {:ok, view, _html} =
        conn
        |> log_in_user(user)
        |> live(~p"/orgs/#{org.slug}/settings/integrations")

      view |> element("#configure-preseem") |> render_click()

      view
      |> form("#preseem-form", %{integration: %{api_key: "test-key-123"}})
      |> render_submit()

      assert {:ok, integration} = Towerops.Integrations.get_integration(org.id, "preseem")
      assert integration.credentials["api_key"] == "test-key-123"
    end

    test "can test preseem connection successfully", %{conn: conn, user: user, organization: org} do
      Req.Test.stub(PreseemClient, fn conn ->
        Req.Test.json(conn, %{
          "data" => [%{"id" => 1, "name" => "Test AP"}],
          "paginator" => %{"page" => 1, "page_count" => 1, "limit" => 100, "total_count" => 1}
        })
      end)

      {:ok, view, _html} =
        conn
        |> log_in_user(user)
        |> live(~p"/orgs/#{org.slug}/settings/integrations")

      view |> element("#configure-preseem") |> render_click()

      view
      |> form("#preseem-form", %{integration: %{api_key: "test-key"}})
      |> render_change()

      html = view |> element("#test-connection") |> render_click()
      assert html =~ "Connection successful"
    end
  end
end
