package modshared

import (
	"context"
	"log/slog"

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

type RPCAPIStub struct {
	StreamCtx context.Context //nolint:containedctx
	Logger    *slog.Logger
}

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

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