package modshared

import (
	"context"
	"log/slog"

	"gitlab.com/gitlab-org/cluster-integration/gitlab-agent/v18/internal/tool/errz"
	"gitlab.com/gitlab-org/cluster-integration/gitlab-agent/v18/internal/tool/grpctool"
	"gitlab.com/gitlab-org/cluster-integration/gitlab-agent/v18/internal/tool/retry"
)

type RPCAPIStub struct {
	StreamCtx context.Context
	Logger    *slog.Logger
}

func (a *RPCAPIStub) PollWithBackoff(cfg retry.PollConfig, f retry.PollWithBackoffFunc) error {
	// this context must only be used here, not inside of f() - connection should be closed only when idle.
	ageCtx := grpctool.MaxConnectionAgeContextFromStreamContext(a.StreamCtx)
	err := retry.PollWithBackoff(ageCtx, cfg, func(ctx context.Context) (error, retry.AttemptResult) { //nolint:staticcheck
		return f()
	})
	if errz.ContextDone(err) {
		return nil // all good, ctx is done
	}
	return err
}

func (a *RPCAPIStub) Log() *slog.Logger {
	return a.Logger
}
