package api

import (
	"context"
	"net/url"

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

const (
	ProjectIDQueryParam        = "id"
	VerifyProjectAccessAPIPath = "/api/v4/internal/kubernetes/verify_project_access"
)

func VerifyProjectAccess(ctx context.Context, client gitlab.ClientInterface, agentTokenWithType api.AgentTokenWithType, projectID string, opts ...gitlab.DoOption) (bool, error) {
	err := client.Do(ctx,
		joinOpts(opts,
			gitlab.WithPath(VerifyProjectAccessAPIPath),
			gitlab.WithQuery(url.Values{
				ProjectIDQueryParam: []string{projectID},
			}),
			gitlab.WithAgentTokenAndType(agentTokenWithType),
			gitlab.WithResponseHandler(gitlab.NoContentResponseHandler()),
			gitlab.WithJWT(true),
		)...,
	)
	if err == nil {
		return true, nil
	}

	if gitlab.IsForbidden(err) || gitlab.IsUnauthorized(err) || gitlab.IsNotFound(err) {
		return false, nil
	}

	return false, err
}
