// Package engine provides a mode-agnostic scan engine that can be used
// independently of any UI layer. This file defines engine configuration.
package engine

import (
	"errors"
	"time"
)

// Worker count constraints for CLI validation
const (
	MinWorkers     = 3
	MaxWorkers     = 1000
	DefaultWorkers = 1000
)

// Config holds configuration for the scan engine.
// Use DefaultConfig() to get sensible defaults, then modify as needed.
type Config struct {
	// Workers is the number of concurrent workers per scan.
	// Each worker processes one target at a time.
	// Default: 10
	Workers int

	// Timeout is the per-request HTTP timeout.
	// This is a backstop timeout covering the entire request lifecycle.
	// Default: 10s
	Timeout time.Duration

	// BufferSize is the capacity of the circular buffer for output.
	// When full, oldest items are dropped (display-only; findings persist to DB).
	// Default: 1000
	BufferSize int

	// BatchInterval is the interval for batching progress updates.
	// Updates are aggregated and delivered at this interval to avoid overwhelming consumers.
	// Default: 100ms
	BatchInterval time.Duration

	// ShutdownTimeout is the maximum time to wait for graceful shutdown.
	// After this timeout, in-flight requests are abandoned and reported as incomplete.
	// Default: 30s
	ShutdownTimeout time.Duration
}

// DefaultConfig returns a Config with sensible defaults.
// Workers: 1000, Timeout: 5s, BufferSize: 1000, BatchInterval: 100ms, ShutdownTimeout: 30s
func DefaultConfig() Config {
	return Config{
		Workers:         DefaultWorkers,
		Timeout:         5 * time.Second,
		BufferSize:      1000,
		BatchInterval:   100 * time.Millisecond,
		ShutdownTimeout: 30 * time.Second,
	}
}

// Validate checks that the configuration values are valid.
// Returns an error describing the first invalid value found, or nil if valid.
func (c Config) Validate() error {
	if c.Workers < MinWorkers {
		return errors.New("config: Workers must be at least MinWorkers")
	}
	if c.Workers > MaxWorkers {
		return errors.New("config: Workers must not exceed MaxWorkers")
	}
	if c.Timeout < time.Second {
		return errors.New("config: Timeout must be at least 1 second")
	}
	if c.BufferSize < 1 {
		return errors.New("config: BufferSize must be at least 1")
	}
	if c.BatchInterval < time.Millisecond {
		return errors.New("config: BatchInterval must be at least 1 millisecond")
	}
	if c.ShutdownTimeout < time.Second {
		return errors.New("config: ShutdownTimeout must be at least 1 second")
	}
	return nil
}
