defmodule MicrowavepropWeb.ApiCatalogControllerTest do
  use MicrowavepropWeb.ConnCase, async: true

  describe "GET /.well-known/api-catalog (RFC 9727)" do
    test "returns application/linkset+json with a linkset array", %{conn: conn} do
      conn = get(conn, "/.well-known/api-catalog")

      assert conn.status == 200
      assert ["application/linkset+json" <> _] = get_resp_header(conn, "content-type")

      body = Jason.decode!(conn.resp_body)
      assert is_list(body["linkset"])
      assert body["linkset"] != []
    end

    test "first entry anchors the contacts map endpoint with status and service-desc", %{conn: conn} do
      conn = get(conn, "/.well-known/api-catalog")
      %{"linkset" => [entry | _]} = Jason.decode!(conn.resp_body)

      assert entry["anchor"] =~ "/api/contacts/map"

      assert [%{"href" => status_href}] = entry["status"]
      assert status_href =~ "/health"

      assert [%{"href" => desc_href, "type" => desc_type}] = entry["service-desc"]
      assert desc_href =~ "/openapi.json"
      assert desc_type == "application/vnd.oai.openapi+json;version=3.0"
    end
  end

  describe "GET /openapi.json" do
    test "returns a valid OpenAPI 3.x document describing the public API", %{conn: conn} do
      conn = get(conn, "/openapi.json")

      assert conn.status == 200
      assert ["application/json" <> _] = get_resp_header(conn, "content-type")

      spec = Jason.decode!(conn.resp_body)
      assert spec["openapi"] =~ ~r/^3\./
      assert is_map(spec["info"])
      assert is_binary(spec["info"]["title"])
      assert is_binary(spec["info"]["version"])
      assert Map.has_key?(spec["paths"], "/api/contacts/map")
    end
  end
end
