defmodule Towerops.Workers.GaiiaSyncWorkerTest do
  use Towerops.DataCase, async: true

  import Towerops.AccountsFixtures
  import Towerops.IntegrationsFixtures
  import Towerops.OrganizationsFixtures

  alias Towerops.Gaiia.Client
  alias Towerops.Workers.GaiiaSyncWorker

  setup do
    user = user_fixture()
    org = organization_fixture(user.id)
    integration = integration_fixture(org.id, %{provider: "gaiia"})
    %{org: org, integration: integration}
  end

  describe "perform/1" do
    test "syncs enabled gaiia integrations", %{org: org} do
      stub_all_endpoints()

      assert :ok = GaiiaSyncWorker.perform(%Oban.Job{})

      # Verify data was synced
      assert length(Towerops.Gaiia.list_accounts(org.id)) == 1
    end

    test "skips recently synced integrations", %{integration: integration} do
      # Mark as recently synced
      Towerops.Integrations.update_sync_status(integration, "success")

      # Should skip since it was just synced
      assert :ok = GaiiaSyncWorker.perform(%Oban.Job{})
    end
  end

  defp stub_all_endpoints do
    Req.Test.stub(Client, fn conn ->
      {:ok, body, _conn} = Plug.Conn.read_body(conn)
      decoded = Jason.decode!(body)
      query = decoded["query"]

      response =
        cond do
          String.contains?(query, "ListAccounts") -> accounts_response()
          String.contains?(query, "ListNetworkSites") -> empty_response("networkSites")
          String.contains?(query, "ListInventoryItems") -> empty_response("inventoryItems")
          String.contains?(query, "ListBillingSubscriptions") -> empty_response("billingSubscriptions")
          true -> %{"data" => %{}}
        end

      Req.Test.json(conn, response)
    end)
  end

  defp accounts_response do
    %{
      "data" => %{
        "accounts" => %{
          "edges" => [
            %{
              "node" => %{
                "id" => "acct-1",
                "name" => "Test Account",
                "status" => %{"id" => "status-1", "name" => "Active", "type" => "ACTIVE"},
                "type" => %{"id" => "type-1", "name" => "Residential"},
                "billingSubscriptions" => %{"edges" => []}
              }
            }
          ],
          "pageInfo" => %{"hasNextPage" => false, "endCursor" => nil}
        }
      }
    }
  end

  defp empty_response(root_key) do
    %{
      "data" => %{
        root_key => %{
          "edges" => [],
          "pageInfo" => %{"hasNextPage" => false, "endCursor" => nil}
        }
      }
    }
  end
end
