// Package config provides worker-specific configuration.
package config

import (
	"os"
	"time"

	"github.com/spf13/viper"

	"git.threesix.ai/jordan/persona-community-5/pkg/config"
)

// Config holds media-worker worker configuration.
type Config struct {
	config.AppConfig
	Database config.DatabaseConfig
	Logging  config.LoggingConfig
	Worker   WorkerConfig

	// Redis for publishing SSE events to the service
	RedisURL string
}

// WorkerConfig holds worker-specific settings.
type WorkerConfig struct {
	// PollInterval is how often to check for new jobs when queue is empty.
	PollInterval time.Duration

	// BatchSize is the max number of jobs to process per poll (for batch workers).
	BatchSize int

	// MaxRetries is the default maximum retry attempts for failed jobs.
	MaxRetries int

	// StaleJobTimeout is how long a job can run before being considered stale.
	// Jobs running longer than this without heartbeat will be requeued.
	StaleJobTimeout time.Duration

	// JobTimeout is the maximum time a single job handler can run.
	JobTimeout time.Duration
}

// Load reads configuration from environment variables.
func Load() (*Config, error) {
	if err := config.Init(config.Options{
		AppName: "media-worker",
		SetDefaults: func() {
			viper.SetDefault("WORKER_POLL_INTERVAL", "10s")
			viper.SetDefault("WORKER_BATCH_SIZE", 10)
			viper.SetDefault("WORKER_MAX_RETRIES", 3)
			viper.SetDefault("WORKER_STALE_JOB_TIMEOUT", "5m")
			viper.SetDefault("WORKER_JOB_TIMEOUT", "5m")
		},
	}); err != nil {
		return nil, err
	}

	return &Config{
		AppConfig: config.ReadAppConfig(),
		Database:  config.ReadDatabaseConfig(),
		Logging:   config.ReadLoggingConfig(),
		Worker: WorkerConfig{
			PollInterval:    viper.GetDuration("WORKER_POLL_INTERVAL"),
			BatchSize:       viper.GetInt("WORKER_BATCH_SIZE"),
			MaxRetries:      viper.GetInt("WORKER_MAX_RETRIES"),
			StaleJobTimeout: viper.GetDuration("WORKER_STALE_JOB_TIMEOUT"),
			JobTimeout:      viper.GetDuration("WORKER_JOB_TIMEOUT"),
		},
		RedisURL: os.Getenv("REDIS_URL"),
	}, nil
}
