package server

import (
	"fmt"
	"net/http"
	"net/http/httptest"
	"testing"

	"github.com/pingcap/agent-git-service/internal/rest/transform"
)

func TestServeWithPublicURLBaseScopesLegacyTransformOutput(t *testing.T) {
	transform.Init("https://standalone.example")
	recorder := httptest.NewRecorder()
	request := httptest.NewRequest(http.MethodGet, "/api/v3/repos/acme/docs", nil)

	ServeWithPublicURLBase(http.HandlerFunc(func(writer http.ResponseWriter, _ *http.Request) {
		_, _ = fmt.Fprint(writer, transform.Base()+"/avatars/alice")
	}), recorder, request, "https://agentteam.example/api/v1/workspaces/wsp_1/ags")

	if got, want := recorder.Body.String(), "https://agentteam.example/api/v1/workspaces/wsp_1/ags/avatars/alice"; got != want {
		t.Fatalf("body=%q, want %q", got, want)
	}
	if got := transform.Base(); got != "https://standalone.example" {
		t.Fatalf("process base leaked after request: %q", got)
	}
}

func TestServeWithPublicURLBaseFailsClosedWithoutAuthority(t *testing.T) {
	called := false
	recorder := httptest.NewRecorder()
	ServeWithPublicURLBase(http.HandlerFunc(func(http.ResponseWriter, *http.Request) {
		called = true
	}), recorder, httptest.NewRequest(http.MethodGet, "/", nil), "")
	if recorder.Code != http.StatusInternalServerError || called {
		t.Fatalf("status=%d called=%v", recorder.Code, called)
	}
}
