package task

import (
	"context"
	"time"

	"go.uber.org/zap"

	"github.com/break/junhong_cmp_fiber/pkg/constants"
)

// updateStats 更新监控统计（成功/失败计数 + 耗时）
func (b *PollingBase) updateStats(ctx context.Context, taskType string, success bool, duration time.Duration) {
	key := constants.RedisPollingStatsKey(taskType)
	pipe := b.redis.Pipeline()
	if success {
		pipe.HIncrBy(ctx, key, "success_count_1h", 1)
	} else {
		pipe.HIncrBy(ctx, key, "failure_count_1h", 1)
	}
	pipe.HIncrBy(ctx, key, "total_duration_1h", duration.Milliseconds())
	pipe.Expire(ctx, key, 2*time.Hour)
	_, _ = pipe.Exec(ctx)
}

// insertDataUsageRecord 写入日流量缓冲到 Redis（INCRBYFLOAT + 48h TTL）
func (b *PollingBase) insertDataUsageRecord(ctx context.Context, cardID uint, incrementMB float64, checkTime time.Time) {
	if incrementMB <= 0 {
		return
	}
	dateStr := checkTime.Format("2006-01-02")
	key := constants.RedisCardDailyTrafficKey(cardID, dateStr)
	if err := b.redis.IncrByFloat(ctx, key, incrementMB).Err(); err != nil {
		b.logger.Warn("写入日流量缓冲失败",
			zap.Uint("card_id", cardID), zap.Float64("increment_mb", incrementMB), zap.Error(err))
		return
	}
	b.redis.Expire(ctx, key, 48*time.Hour)
}
