// Package ratelimit enforces the per-user cooldown between creation
// attempts. The daily quota is tracked in the database (see repository), so
// this package only owns the short, in-memory cooldown window.
package ratelimit

import (
	"sync"
	"time"
)

// Limiter is safe for concurrent use. It keeps the last attempt timestamp
// per Telegram user id.
type Limiter struct {
	mu      sync.Mutex
	last    map[int64]time.Time
	coolSec int
}

// New creates a limiter enforcing `coolSec` seconds between calls per user.
func New(coolSec int) *Limiter {
	if coolSec < 0 {
		coolSec = 0
	}
	return &Limiter{last: map[int64]time.Time{}, coolSec: coolSec}
}

// Check reports whether the user may act now. If not, it returns the number of
// seconds until they can.
func (l *Limiter) Check(userID int64) (ok bool, retryIn int) {
	if l.coolSec <= 0 {
		return true, 0
	}
	l.mu.Lock()
	defer l.mu.Unlock()
	last, has := l.last[userID]
	if !has {
		return true, 0
	}
	wait := time.Duration(l.coolSec)*time.Second - time.Since(last)
	if wait <= 0 {
		return true, 0
	}
	return false, int(wait.Round(time.Second).Seconds())
}

// Touch records that the user just attempted an action, starting a new
// cooldown window.
func (l *Limiter) Touch(userID int64) {
	l.mu.Lock()
	defer l.mu.Unlock()
	l.last[userID] = time.Now()
}

// SetCooldown updates the cooldown window (used when an admin changes the
// config from the web panel).
func (l *Limiter) SetCooldown(sec int) {
	l.mu.Lock()
	defer l.mu.Unlock()
	if sec < 0 {
		sec = 0
	}
	l.coolSec = sec
}
