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

  setup do
    conn =
      build_conn()
      |> put_req_header("authorization", "Bearer test-webhook-secret")
      |> put_req_header("accept", "application/json")

    %{conn: conn}
  end

  describe "create/2 authentication" do
    test "returns 401 without authorization" do
      conn =
        build_conn()
        |> put_req_header("accept", "application/json")
        |> post(~p"/api/v1/webhooks/agent-release")

      assert json_response(conn, 401)["error"] == "Missing or invalid Authorization header"
    end

    test "returns 401 with wrong secret" do
      conn =
        build_conn()
        |> put_req_header("authorization", "Bearer wrong-secret")
        |> put_req_header("accept", "application/json")
        |> post(~p"/api/v1/webhooks/agent-release")

      assert json_response(conn, 401)["error"] == "Invalid webhook secret"
    end
  end

  describe "create/2 response" do
    test "returns 502 when GitHub API is unavailable", %{conn: conn} do
      # In test environment, GitHub API returns 404 (private repo, no auth token).
      # The controller should surface this as a 502.
      conn = post(conn, ~p"/api/v1/webhooks/agent-release")

      response = json_response(conn, 502)
      assert response["status"] == "error"
    end
  end
end
