package pkulaw

import (
	"context"
	"sync"

	"github.com/tidbcloud/AgentTeam/internal/extension/runner"
)

type staticConnectionSource struct {
	mu       sync.Mutex
	resolved runner.ResolvedConnection
	err      error
	calls    int
	contract runner.ConnectionConfigContract
}

func (source *staticConnectionSource) ResolveProviderConnection(
	_ context.Context,
	_ string,
	_ string,
	contract runner.ConnectionConfigContract,
) (runner.ResolvedConnection, error) {
	source.mu.Lock()
	defer source.mu.Unlock()
	source.calls++
	source.contract = contract
	if source.err != nil {
		return runner.ResolvedConnection{}, source.err
	}
	return runner.ResolvedConnection{
		Credentials: source.resolved.Credentials.Clone(),
		Config:      source.resolved.Config.Clone(),
	}, nil
}

func (source *staticConnectionSource) snapshot() (int, runner.ConnectionConfigContract) {
	source.mu.Lock()
	defer source.mu.Unlock()
	return source.calls, cloneConnectionConfigContract(source.contract)
}
