package api

import (
	"context"
	"net/http"

	"gitlab.com/gitlab-org/cluster-integration/gitlab-agent/v18/internal/api"
	"gitlab.com/gitlab-org/cluster-integration/gitlab-agent/v18/internal/gitlab"
	"gitlab.com/gitlab-org/cluster-integration/gitlab-agent/v18/internal/tool/httpz"
	"google.golang.org/grpc/mem"
)

const (
	JobsRequestAPIPath = "/api/v4/jobs/request"
)

func GetRawCIJobs(ctx context.Context, client gitlab.ClientInterface, runnerToken api.AgentToken, requestBody []byte,
	opts ...gitlab.DoOption) (int /* HTTP status code */, mem.BufferSlice, string /* response trace ID */, error) {
	var body mem.BufferSlice
	var response *http.Response
	err := client.Do(ctx,
		joinOpts(opts,
			gitlab.WithMethod(http.MethodPost),
			gitlab.WithPath(JobsRequestAPIPath),
			gitlab.WithHeader(http.Header{
				httpz.RunnerTokenHeader: []string{string(runnerToken)},
			}),
			gitlab.WithRequestBodyBytes(requestBody, "application/json"),
			gitlab.WithResponseHandler(
				gitlab.MultiResponseHandler(
					gitlab.NakedResponseHandler(&response),
					gitlab.RawBodyResponseHandler(
						[]int{http.StatusCreated, http.StatusNoContent},
						"application/json",
						&body,
					),
				),
			),
		)...,
	)

	requestID := ""
	if response != nil {
		requestID = response.Header.Get(httpz.RequestIDHeader)
	}

	if err != nil {
		return 0, nil, requestID, err
	}
	return response.StatusCode, body, requestID, nil
}
