package config

import (
	"fmt"
	"time"
)

// SecurityConfig holds security-related configuration
type SecurityConfig struct {
	AuditLogging       AuditLoggingConfig `yaml:"audit_logging"`
	AllowedOrigins     []string           `yaml:"allowed_origins"`
	IPWhitelist        []string           `yaml:"ip_whitelist"`
	APIKeyRotationDays int                `yaml:"api_key_rotation_days"`
	ProductionMode     bool               `yaml:"production_mode"`
}

// AuditLoggingConfig holds audit logging configuration
type AuditLoggingConfig struct {
	LogPath string `yaml:"log_path"`
	Enabled bool   `yaml:"enabled"`
}

// PrivacyConfig holds privacy enforcement configuration
type PrivacyConfig struct {
	DefaultLevel string `yaml:"default_level"`
	Enabled      bool   `yaml:"enabled"`
	EnforceTeams bool   `yaml:"enforce_teams"`
	AuditAccess  bool   `yaml:"audit_access"`
}

// Validate checks privacy configuration
func (p *PrivacyConfig) Validate() error {
	if !p.Enabled {
		return nil
	}
	validLevels := map[string]bool{"private": true, "team": true, "public": true, "anonymized": true}
	if p.DefaultLevel != "" && !validLevels[p.DefaultLevel] {
		return fmt.Errorf("invalid default privacy level: %s", p.DefaultLevel)
	}
	return nil
}

// MonitoringConfig holds monitoring-related configuration
type MonitoringConfig struct {
	Prometheus   PrometheusConfig   `yaml:"prometheus"`
	HealthChecks HealthChecksConfig `yaml:"health_checks"`
}

// PrometheusConfig holds Prometheus metrics configuration
type PrometheusConfig struct {
	Path    string `yaml:"path"`
	Port    int    `yaml:"port"`
	Enabled bool   `yaml:"enabled"`
}

// HealthChecksConfig holds health check configuration
type HealthChecksConfig struct {
	Enabled  bool          `yaml:"enabled"`
	Interval time.Duration `yaml:"interval"`
}

// Validate validates the security configuration
func (s *SecurityConfig) Validate() error {
	if s.ProductionMode {
		if len(s.AllowedOrigins) == 0 {
			return fmt.Errorf("production_mode requires at least one allowed_origin")
		}
	}

	if s.APIKeyRotationDays < 0 {
		return fmt.Errorf("api_key_rotation_days must be positive")
	}

	if s.AuditLogging.Enabled && s.AuditLogging.LogPath == "" {
		return fmt.Errorf("audit_logging enabled but log_path not set")
	}

	return nil
}

// Validate validates the monitoring configuration
func (m *MonitoringConfig) Validate() error {
	if m.Prometheus.Enabled {
		if m.Prometheus.Port <= 0 || m.Prometheus.Port > 65535 {
			return fmt.Errorf("prometheus port must be between 1 and 65535")
		}
		if m.Prometheus.Path == "" {
			m.Prometheus.Path = "/metrics" // Default
		}
	}

	return nil
}
