package runner

import (
	"bytes"
	"context"
	"encoding/json"
	"errors"
	"net/http"
	"strings"

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

// httpExecutionTransport is the first platform-neutral Worker transport
// adapter. The routing core sees only WorkerDescriptor and executionpool's
// versioned request/response types; Pod DNS and other orchestrator concepts do
// not cross this boundary.
type httpExecutionTransport struct {
	client *http.Client
}

func (transport httpExecutionTransport) Execute(
	ctx context.Context,
	worker executionpool.WorkerDescriptor,
	input executionpool.ExecutionRequest,
) (executionpool.ExecutionResponse, error) {
	if transport.client == nil {
		return executionpool.ExecutionResponse{}, errors.New("worker HTTP client is required")
	}
	payload, err := json.Marshal(InternalExecutionRequest{
		TaskID:  input.TaskID,
		LeaseID: input.LeaseID,
		Stream:  input.Stream,
	})
	if err != nil {
		return executionpool.ExecutionResponse{}, err
	}
	request, err := http.NewRequestWithContext(
		ctx,
		http.MethodPost,
		strings.TrimRight(worker.Endpoint, "/")+workerExecutionPath,
		bytes.NewReader(payload),
	)
	if err != nil {
		return executionpool.ExecutionResponse{}, err
	}
	request.Header.Set("Content-Type", "application/json")
	request.Header.Set("Authorization", "Worker "+input.AuthorizationToken)
	response, err := transport.client.Do(request)
	if err != nil {
		return executionpool.ExecutionResponse{}, err
	}
	return executionpool.ExecutionResponse{
		StatusCode: response.StatusCode,
		Headers:    response.Header,
		Body:       response.Body,
	}, nil
}

var _ executionpool.ExecutionTransport = httpExecutionTransport{}
