package util

import "time"

// 判断当前时间是否在时间窗口内
// ts 时间戳字符串，支持秒级或毫秒级
// window 时间窗口，例如 10 * time.Minute
func IsInTimeWindow(ts string, window time.Duration) bool {
	// 期望毫秒时间戳或秒级，简单容错
	// 尝试解析为整数
	var n int64
	for _, base := range []int64{1, 1000} { // 秒或毫秒
		if v, ok := parseInt64(ts); ok {
			n = v
			// 归一为毫秒
			if base == 1 && len(ts) <= 10 {
				n = n * 1000
			}
			now := time.Now().UnixMilli()
			diff := now - n
			if diff < 0 {
				diff = -diff
			}
			if diff <= window.Milliseconds() {
				return true
			}
		}
	}
	return false
}

func parseInt64(s string) (int64, bool) {
	var n int64
	for _, ch := range s {
		if ch < '0' || ch > '9' {
			return 0, false
		}
		n = n*10 + int64(ch-'0')
	}
	return n, true
}
