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) (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,
					),
				),
			),
		)...,
	)
	if err != nil {
		return nil, "", err
	}
	return body, response.Header.Get(httpz.RequestIDHeader), nil
}
