defmodule ToweropsWeb.Api.V1.GeoipControllerTest do
  use ToweropsWeb.ConnCase, async: true

  import Towerops.AccountsFixtures
  import Towerops.OrganizationsFixtures

  alias Towerops.ApiTokens

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

    {:ok, {_token, raw_token}} =
      ApiTokens.create_api_token(%{
        organization_id: organization.id,
        user_id: user.id,
        name: "Test Token"
      })

    conn =
      build_conn()
      |> put_req_header("authorization", "Bearer #{raw_token}")
      |> put_req_header("accept", "application/json")
      |> put_req_header("content-type", "application/json")

    %{conn: conn, user: user, organization: organization}
  end

  describe "import_database" do
    test "returns forbidden for non-superuser", %{conn: conn} do
      conn =
        post(conn, "/admin/api/geoip/import", %{
          "batch_type" => "locations",
          "data" => []
        })

      assert json_response(conn, 403)["error"] =~ "Superuser access required"
    end

    test "imports locations batch for superuser", %{conn: conn, user: user} do
      user |> Ecto.Changeset.change(%{is_superuser: true}) |> Towerops.Repo.update!()

      conn =
        post(conn, "/admin/api/geoip/import", %{
          "batch_type" => "locations",
          "data" => [],
          "truncate" => false
        })

      assert json_response(conn, 200)["status"] == "ok"
    end

    test "returns error for invalid batch type", %{conn: conn, user: user} do
      user |> Ecto.Changeset.change(%{is_superuser: true}) |> Towerops.Repo.update!()

      conn =
        post(conn, "/admin/api/geoip/import", %{
          "batch_type" => "invalid",
          "data" => []
        })

      assert json_response(conn, 500)["error"] =~ "Invalid batch_type"
    end
  end
end
