package qichacha

import (
	"crypto/md5"
	"encoding/hex"
	"strconv"
	"strings"
	"time"

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

// signatureHeaders derives the per-request Timespan and Token headers from
// the connection credential pair: Token is the upper-case MD5 of
// AppKey+Timespan+SecretKey, exactly as the Qichacha OpenAPI contract
// specifies. The runtime applies them as the provider's credential
// injection, computed per call so a captured Token never replays on another
// timespan.
func signatureHeaders(credentials runner.Credentials) (map[string]string, error) {
	appKey := strings.TrimSpace(credentials["appKey"])
	secretKey := strings.TrimSpace(credentials["secretKey"])
	timespan := strconv.FormatInt(time.Now().Unix(), 10)
	digest := md5.Sum([]byte(appKey + timespan + secretKey))
	return map[string]string{
		"Timespan": timespan,
		"Token":    strings.ToUpper(hex.EncodeToString(digest[:])),
	}, nil
}
