package runner

import (
	"context"
	"encoding/json"
	"io"
	"net/http"
	"net/http/httptest"
	"testing"

	"github.com/easyai/easyai-ai-gateway/apps/api/internal/executionpool"
)

func TestHTTPExecutionTransportUsesAdvertisedEndpointAndProtocol(t *testing.T) {
	server := httptest.NewServer(http.HandlerFunc(func(response http.ResponseWriter, request *http.Request) {
		if request.URL.Path != workerExecutionPath {
			t.Fatalf("path=%q", request.URL.Path)
		}
		if got := request.Header.Get("Authorization"); got != "Worker signed-token" {
			t.Fatalf("authorization=%q", got)
		}
		var payload InternalExecutionRequest
		if err := json.NewDecoder(request.Body).Decode(&payload); err != nil {
			t.Fatal(err)
		}
		if payload.TaskID != "task-1" || payload.LeaseID != "lease-1" || !payload.Stream {
			t.Fatalf("payload=%+v", payload)
		}
		response.Header().Set("X-Worker", "accepted")
		response.WriteHeader(http.StatusAccepted)
		_, _ = response.Write([]byte("ok"))
	}))
	defer server.Close()

	transport := httpExecutionTransport{client: server.Client()}
	result, err := transport.Execute(context.Background(), executionpool.WorkerDescriptor{
		WorkerID: "worker-1", PoolID: "pool-1", Endpoint: server.URL,
	}, executionpool.ExecutionRequest{
		TaskID: "task-1", PoolID: "pool-1", WorkerID: "worker-1", LeaseID: "lease-1",
		AuthorizationToken: "signed-token", Stream: true,
	})
	if err != nil {
		t.Fatal(err)
	}
	defer result.Body.Close()
	body, err := io.ReadAll(result.Body)
	if err != nil {
		t.Fatal(err)
	}
	if result.StatusCode != http.StatusAccepted || len(result.Headers["X-Worker"]) != 1 || result.Headers["X-Worker"][0] != "accepted" || string(body) != "ok" {
		t.Fatalf("result=%+v body=%q", result, body)
	}
}
