package middleware

import "time"

// Clear 登录成功后清除该 email 和 IP 的失败计数
func (rl *RateLimiter) Clear(email, ip string) {
	rl.mu.Lock()
	defer rl.mu.Unlock()
	delete(rl.accountFailures, email)
	delete(rl.ipFailures, ip)
}

// ClearIP 按 IP key 清除失败计数（用于注册等仅 IP 维度的限流）
func (rl *RateLimiter) ClearIP(ipKey string) {
	rl.mu.Lock()
	defer rl.mu.Unlock()
	delete(rl.ipFailures, ipKey)
}

// cleanupLoop 定期清理过期条目
func (rl *RateLimiter) cleanupLoop() {
	ticker := time.NewTicker(cleanupInterval)
	defer ticker.Stop()
	for range ticker.C {
		rl.mu.Lock()
		now := time.Now()
		clean := func(m map[string]*windowState) {
			for k, v := range m {
				if (v.blockedUntil.IsZero() || now.After(v.blockedUntil)) &&
					now.Sub(v.windowStart) > accountWindow+ipBlockDur {
					delete(m, k)
				}
			}
		}
		clean(rl.accountFailures)
		clean(rl.ipFailures)
		rl.mu.Unlock()
	}
}
