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/featureflag"
)

const (
	AuthorizeProxyUserAPIPath = "/api/v4/internal/kubernetes/authorize_proxy_user"

	SessionCookieAccessType       AccessType = "session_cookie"
	PersonalAccessTokenAccessType AccessType = "personal_access_token"
)

// AccessType represents the type of the access key when authorizing proxy users.
// These values must match the possible values accepted by the Rails API and
// the ones from api.proto of this package. See AuthorizeProxyUserRequest message.
type AccessType string

type AuthorizeProxyUserResponse struct {
	Response     *AuthorizeProxyUserAPIResponse
	FeatureFlags featureflag.Set
}

func AuthorizeProxyUser(ctx context.Context, client gitlab.ClientInterface, agentKey api.AgentKey, accessType AccessType, accessKey, csrfToken string, opts ...gitlab.DoOption) (*AuthorizeProxyUserResponse, error) {
	auth := &AuthorizeProxyUserAPIResponse{}
	var ffs featureflag.Set
	err := client.Do(ctx,
		joinOpts(opts,
			gitlab.WithMethod(http.MethodPost),
			gitlab.WithPath(AuthorizeProxyUserAPIPath),
			gitlab.WithJWT(true),
			gitlab.WithProtoJSONRequestBody(&AuthorizeProxyUserAPIRequest{
				AgentId:    agentKey.ID,
				AccessType: string(accessType),
				AccessKey:  accessKey,
				CsrfToken:  csrfToken,
			}),
			gitlab.WithResponseHandler(gitlab.ProtoJSONResponseHandlerWithStructuredErrReason(auth)),
			gitlab.WithFeatureFlags(&ffs),
		)...,
	)
	if err != nil {
		return nil, err
	}
	return &AuthorizeProxyUserResponse{
		Response:     auth,
		FeatureFlags: ffs,
	}, nil
}
