package sign

import (
	"crypto/hmac"
	"crypto/sha256"
	"encoding/base64"
	"net/url"
	"strconv"
	"time"

	"sms-receiver-go/config"
)

// GenerateSign 生成签名
func GenerateSign(timestamp int64, secret string) (string, error) {
	if secret == "" {
		return "", nil
	}

	stringToSign := strconv.FormatInt(timestamp, 10) + "\n" + secret

	hmacCode := hmac.New(sha256.New, []byte(secret))
	hmacCode.Write([]byte(stringToSign))
	signBytes := hmacCode.Sum(nil)

	// Base64 编码
	signBase64 := base64.StdEncoding.EncodeToString(signBytes)

	// URL 编码
	sign := url.QueryEscape(signBase64)

	return sign, nil
}

// VerifySign 验证签名
func VerifySign(token string, timestamp int64, sign string, cfg *config.SecurityConfig) (bool, error) {
	if !cfg.SignVerify || token == "" {
		return true, nil
	}

	// 查找对应的 secret
	tokenConfig := config.Get().GetTokenByValue(token)
	if tokenConfig == nil {
		return false, nil
	}

	secret := tokenConfig.Secret
	if secret == "" {
		// 无 secret，跳过签名验证
		return true, nil
	}

	// 检查时间戳是否过期
	currentTime := time.Now().UnixMilli()
	if currentTime-timestamp > cfg.SignMaxAge {
		return false, nil // 时间戳过期
	}

	// 重新生成签名进行比较
	expectedSign, err := GenerateSign(timestamp, secret)
	if err != nil {
		return false, err
	}

	// 比较签名
	return sign == expectedSign, nil
}
