package cpnotice

import (
	"strings"
	"time"
)

// CPNoticeWorkerOptions mirrors other notice workers but is MQ-driven; the lock still protects per-channel delivery rows.
type CPNoticeWorkerOptions struct {
	WorkerID       string
	BatchSize      int
	LockTTL        time.Duration
	PublishTimeout time.Duration
	MaxRetryCount  int
	InitialBackoff time.Duration
	MaxBackoff     time.Duration
}

func normalizeCPNoticeWorkerOptions(options CPNoticeWorkerOptions, nodeID string) CPNoticeWorkerOptions {
	if strings.TrimSpace(options.WorkerID) == "" {
		options.WorkerID = strings.TrimSpace(nodeID)
	}
	if options.WorkerID == "" {
		options.WorkerID = "notice-cp-worker"
	}
	if options.BatchSize <= 0 {
		options.BatchSize = 100
	}
	if options.LockTTL <= 0 {
		options.LockTTL = 30 * time.Second
	}
	if options.PublishTimeout <= 0 {
		options.PublishTimeout = 3 * time.Second
	}
	if options.MaxRetryCount <= 0 {
		options.MaxRetryCount = 10
	}
	if options.InitialBackoff <= 0 {
		options.InitialBackoff = 5 * time.Second
	}
	if options.MaxBackoff <= 0 {
		options.MaxBackoff = 5 * time.Minute
	}
	return options
}

func cpNoticeBackoff(retryCount int, options CPNoticeWorkerOptions) time.Duration {
	if retryCount <= 0 {
		return options.InitialBackoff
	}
	backoff := options.InitialBackoff
	for i := 1; i < retryCount; i++ {
		backoff *= 2
		if backoff >= options.MaxBackoff {
			return options.MaxBackoff
		}
	}
	return backoff
}
