defmodule Towerops.Workers.GaiiaInsightWorkerTest do
  use Towerops.DataCase, async: false
  use Oban.Testing, repo: Towerops.Repo

  import Towerops.AccountsFixtures
  import Towerops.DevicesFixtures
  import Towerops.OrganizationsFixtures

  alias Towerops.Integrations
  alias Towerops.Preseem.Insights
  alias Towerops.Workers.GaiiaInsightWorker

  setup do
    user = user_fixture()
    org = organization_fixture(user.id)

    %{org: org}
  end

  describe "perform/1" do
    test "returns :ok with no gaiia integrations" do
      assert :ok = perform_job(GaiiaInsightWorker, %{})
    end

    test "generates reconciliation_finding for untracked devices", %{org: org} do
      setup_gaiia_integration(org)

      # Create a device that has no Gaiia inventory item mapped
      _device = device_fixture(%{organization_id: org.id})

      assert :ok = perform_job(GaiiaInsightWorker, %{})

      insights = Insights.list_insights(org.id, type: "reconciliation_finding")
      assert insights != []
      assert hd(insights).source == "gaiia"
    end

    test "does not duplicate reconciliation insights on repeated runs", %{org: org} do
      setup_gaiia_integration(org)
      _device = device_fixture(%{organization_id: org.id})

      assert :ok = perform_job(GaiiaInsightWorker, %{})
      first_count = length(Insights.list_insights(org.id, source: "gaiia"))

      assert :ok = perform_job(GaiiaInsightWorker, %{})
      second_count = length(Insights.list_insights(org.id, source: "gaiia"))

      assert first_count == second_count
    end
  end

  defp setup_gaiia_integration(org) do
    {:ok, _integration} =
      Integrations.create_integration(org.id, %{
        provider: "gaiia",
        enabled: true,
        config: %{"api_key" => "test-key"}
      })
  end
end
