package config

import "time"

type Config struct {
	App      AppConfig      `mapstructure:"app"`
	HTTP     HTTPConfig     `mapstructure:"http"`
	Log      LogConfig      `mapstructure:"log"`
	Auth     AuthConfig     `mapstructure:"auth"`
	Database DatabaseConfig `mapstructure:"database"`
	Redis    RedisConfig    `mapstructure:"redis"`
	JWT      JWTConfig      `mapstructure:"jwt"`
	OAuth    OAuthConfig    `mapstructure:"oauth"`
	Storage  StorageConfig  `mapstructure:"storage"`
	Scan     ScanConfig     `mapstructure:"scan"`
	Agent    AgentConfig    `mapstructure:"agent"`
	Audit    AuditConfig    `mapstructure:"audit"`
}

type AuditConfig struct {
	RetentionDays int `mapstructure:"retention_days"` // <=0 时按 90 天兜底
}

type AppConfig struct {
	Name        string `mapstructure:"name"`
	Environment string `mapstructure:"environment"`
	Version     string `mapstructure:"version"`
}

type HTTPConfig struct {
	Host              string        `mapstructure:"host"`
	Port              int           `mapstructure:"port"`
	ReadTimeout       time.Duration `mapstructure:"read_timeout"`
	WriteTimeout      time.Duration `mapstructure:"write_timeout"`
	ShutdownTimeout   time.Duration `mapstructure:"shutdown_timeout"`
	CORSAllowedOrigin []string      `mapstructure:"allowed_origins"`
	GzipEnabled       bool          `mapstructure:"gzip_enabled"`
	GzipLevel         int           `mapstructure:"gzip_level"`
	GzipMinBytes      int           `mapstructure:"gzip_min_bytes"`
}

type LogConfig struct {
	Level  string `mapstructure:"level"`
	Format string `mapstructure:"format"`
}

type AuthConfig struct {
	BypassSSO bool          `mapstructure:"bypass_sso"`
	DevUser   DevUserConfig `mapstructure:"dev_user"`
}

type DevUserConfig struct {
	ID    string   `mapstructure:"id"`
	Email string   `mapstructure:"email"`
	Name  string   `mapstructure:"name"`
	Roles []string `mapstructure:"roles"`
}

type DatabaseConfig struct {
	DSN             string        `mapstructure:"dsn"`
	MaxOpenConns    int           `mapstructure:"max_open_conns"`
	MaxIdleConns    int           `mapstructure:"max_idle_conns"`
	ConnMaxLifetime time.Duration `mapstructure:"conn_max_lifetime"`
}

type RedisConfig struct {
	Addr         string        `mapstructure:"addr"`
	Password     string        `mapstructure:"password"`
	DB           int           `mapstructure:"db"`
	PoolSize     int           `mapstructure:"pool_size"`
	MinIdleConns int           `mapstructure:"min_idle_conns"`
	DialTimeout  time.Duration `mapstructure:"dial_timeout"`
	ReadTimeout  time.Duration `mapstructure:"read_timeout"`
	WriteTimeout time.Duration `mapstructure:"write_timeout"`
}

type JWTConfig struct {
	AccessSecret        string        `mapstructure:"access_secret"`
	RefreshSecret       string        `mapstructure:"refresh_secret"`
	AccessTokenTTL      time.Duration `mapstructure:"access_token_ttl"`
	RefreshTokenTTL     time.Duration `mapstructure:"refresh_token_ttl"`
	RefreshGracePeriod  time.Duration `mapstructure:"refresh_grace_period"`
	SigningAlgorithm    string        `mapstructure:"signing_algorithm"`
	Issuer              string        `mapstructure:"issuer"`
	ClockSkewInSeconds  int64         `mapstructure:"clock_skew_seconds"`
	AllowInsecureSecret bool          `mapstructure:"allow_insecure_secret"`
}

type OAuthConfig struct {
	Enabled            bool     `mapstructure:"enabled"`
	Provider           string   `mapstructure:"provider"`
	ClientID           string   `mapstructure:"client_id"`            // legacy google client id
	ClientSecret       string   `mapstructure:"client_secret"`        // legacy google client secret
	GoogleClientID     string   `mapstructure:"google_client_id"`     // preferred google client id
	GoogleClientSecret string   `mapstructure:"google_client_secret"` // preferred google client secret
	Auth0Domain        string   `mapstructure:"auth0_domain"`
	Auth0ClientID      string   `mapstructure:"auth0_client_id"`
	Auth0ClientSecret  string   `mapstructure:"auth0_client_secret"`
	Auth0Audience      string   `mapstructure:"auth0_audience"`
	RedirectURL        string   `mapstructure:"redirect_url"`
	Scopes             []string `mapstructure:"scopes"`
	BypassGoogle       bool     `mapstructure:"bypass_google"`   // For development: skip real provider
	BypassProvider     bool     `mapstructure:"bypass_provider"` // Generalized bypass flag
}

type StorageConfig struct {
	Provider string   `mapstructure:"provider"` // s3
	S3       S3Config `mapstructure:"s3"`
}

type S3Config struct {
	Enabled         bool          `mapstructure:"enabled"`
	Bucket          string        `mapstructure:"bucket"`
	Region          string        `mapstructure:"region"`
	AccessKeyID     string        `mapstructure:"access_key_id"`
	SecretAccessKey string        `mapstructure:"secret_access_key"`
	Endpoint        string        `mapstructure:"endpoint"`
	// PublicEndpoint 可选: 生成预签名 URL 时使用的对外可达地址
	// (如本地 docker 环境宿主机访问 MinIO 用 http://localhost:19000)。
	// 为空时预签名 URL 沿用 Endpoint(假定客户端与服务端同一网络)。
	PublicEndpoint  string        `mapstructure:"public_endpoint"`
	UsePathStyle    bool          `mapstructure:"use_path_style"`
	BaseURL         string        `mapstructure:"base_url"`
	UploadPrefix    string        `mapstructure:"upload_prefix"`
	PresignTTL      time.Duration `mapstructure:"presign_ttl"`
}

type ScanConfig struct {
	Scanner ScannerConfig `mapstructure:"scanner"`
}

type ScannerConfig struct {
	Enabled                    bool          `mapstructure:"enabled"`
	BaseURL                    string        `mapstructure:"base_url"`
	APIToken                   string        `mapstructure:"api_token"`
	CallbackToken              string        `mapstructure:"callback_token"`
	Timeout                    time.Duration `mapstructure:"timeout"`
	UserAgent                  string        `mapstructure:"user_agent"`
	MaxTargetsPerBatch         int           `mapstructure:"max_targets_per_batch"`
	MaxCampaignTargets         int           `mapstructure:"max_campaign_targets"`
	CampaignSubmitConcurrency  int           `mapstructure:"campaign_submit_concurrency"`
	CampaignDispatcherInterval time.Duration `mapstructure:"campaign_dispatcher_interval"`
	AllowNonPublicTargets      bool          `mapstructure:"allow_non_public_targets"`
}

type AgentConfig struct {
	Enabled           bool   `mapstructure:"enabled"`             // 总开关, 关则 X-API-Key 全拒
	KeyPrefix         string `mapstructure:"key_prefix"`          // "sk-agent-"
	AllowPermanentKey bool   `mapstructure:"allow_permanent_key"` // 生产必须 false; Phase 2 启用
	QuotaEnabled      bool   `mapstructure:"quota_enabled"`       // Phase 3 启用
	DefaultQuotaRPM   int    `mapstructure:"default_quota_rpm"`   // Phase 3 启用
}
