defmodule ToweropsWeb.Api.V1.MibControllerTest 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")

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

  describe "index" do
    test "returns forbidden for non-superuser", %{conn: conn} do
      conn = get(conn, "/admin/api/mibs")

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

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

      conn = get(conn, "/admin/api/mibs")

      assert json_response(conn, 200)
    end
  end

  describe "upload" do
    test "returns forbidden for non-superuser", %{conn: conn} do
      conn = post(conn, "/admin/api/mibs", %{})

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

    test "returns bad request when file is missing for superuser", %{conn: conn, user: user} do
      user |> Ecto.Changeset.change(%{is_superuser: true}) |> Towerops.Repo.update!()

      conn = post(conn, "/admin/api/mibs", %{})

      assert json_response(conn, 400)["error"] =~ "Missing file"
    end
  end

  describe "delete" do
    test "returns forbidden for non-superuser", %{conn: conn} do
      conn = delete(conn, "/admin/api/mibs/testvendor")

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