package api

import (
	"context"
	"net/url"
	"strconv"

	"gitlab.com/gitlab-org/cluster-integration/gitlab-agent/v18/internal/gitlab"
)

const (
	AuthorizeUserWorkspaceAccessAPIPath = "/api/v4/internal/agents/agentw/authorize_user_access"

	HostQueryParam   = "workspace_host"
	UserIDQueryParam = "user_id"
)

func AuthorizeUserWorkspaceAccess(ctx context.Context, client gitlab.ClientInterface, workspaceHost string, userID int64, opts ...gitlab.DoOption) (*AuthorizeUserWorkspaceAccessResponse, error) {
	response := &AuthorizeUserWorkspaceAccessResponse{}
	err := client.Do(ctx,
		joinOpts(opts,
			gitlab.WithPath(AuthorizeUserWorkspaceAccessAPIPath),
			gitlab.WithQuery(url.Values{
				HostQueryParam:   []string{workspaceHost},
				UserIDQueryParam: []string{strconv.FormatInt(userID, 10)},
			}),
			gitlab.WithResponseHandler(gitlab.ProtoJSONResponseHandler(response)),
			gitlab.WithJWT(true),
		)...,
	)
	if err != nil {
		return nil, err
	}
	return response, nil
}
