// Package config provides configuration management for AutoSSO.
// It defines all configuration structures for loading settings from YAML files
// and environment variables.
package config

import (
	"time"
)

// Config is the root configuration structure for AutoSSO application.
// It contains all configuration sections including Feishu integration,
// database connection, cloud providers, and runtime settings.
//
// Requirements: 2.1-2.8, 9.1
type Config struct {
	// Feishu contains Feishu (Lark) integration configuration
	Feishu FeishuConfig `yaml:"feishu"`

	// Database contains MySQL database connection configuration
	Database DatabaseConfig `yaml:"database"`

	// Providers contains cloud platform provider configurations
	Providers ProvidersConfig `yaml:"providers"`

	// Runtime contains runtime behavior configuration
	Runtime RuntimeConfig `yaml:"runtime"`

	// PermissionMappings contains Feishu permission name to real permission name mappings
	// This is used for AWS and general permission name translation
	PermissionMappings []PermissionMapping `yaml:"permission_mappings"`

	// GCPRoleMappings contains custom role to GCP IAM roles mappings
	// This replaces the gcp_custom_role.ini file configuration
	// Requirements: 9.6, 10.4
	GCPRoleMappings []GCPRoleMapping `yaml:"gcp_role_mappings"`
}

// FeishuConfig contains Feishu (Lark) API configuration.
//
// Requirements: 2.1, 2.8
type FeishuConfig struct {
	// AppID is the Feishu application ID
	// Can be overridden by FEISHU_APP_ID environment variable
	AppID string `yaml:"app_id" env:"FEISHU_APP_ID"`

	// AppSecret is the Feishu application secret
	// Can be overridden by FEISHU_APP_SECRET environment variable
	AppSecret string `yaml:"app_secret" env:"FEISHU_APP_SECRET"`

	// ApprovalCode is the approval flow definition code
	ApprovalCode string `yaml:"approval_code"`

	// ChatID is the Feishu group chat ID for notifications
	ChatID string `yaml:"chat_id"`

	// BaseURL is the Feishu API base URL
	// Default: https://open.feishu.cn
	BaseURL string `yaml:"base_url" default:"https://open.feishu.cn"`

	// FieldMappings contains optional custom field name patterns
	// If not specified, default patterns are used by the parser
	FieldMappings *FeishuFieldMappings `yaml:"field_mappings,omitempty"`
}

// FeishuFieldMappings defines configurable field name patterns for parsing
// Feishu approval forms. Each field contains a list of keywords that the
// parser will match (case-insensitive) to identify form fields.
//
// If this configuration is not provided, the parser uses built-in defaults.
type FeishuFieldMappings struct {
	// Email contains keywords to identify email fields
	// Default: ["申请人邮箱", "邮箱", "applicant email"]
	Email []string `yaml:"email,omitempty"`

	// AppType contains keywords to identify application type fields
	// Default: ["申请类型", "申请人选择申请类型"]
	AppType []string `yaml:"app_type,omitempty"`

	// Account contains cloud-specific keywords for account fields
	// Key is the cloud type (alibaba, aws, gcp, azure), value is keyword list
	Account map[string][]string `yaml:"account,omitempty"`

	// Permission contains cloud-specific keywords for permission/role fields
	// Key is the cloud type (alibaba, aws, gcp, azure), value is keyword list
	Permission map[string][]string `yaml:"permission,omitempty"`

	// StartTime contains keywords to identify start time fields
	// Default: ["start time", "开始时间"]
	StartTime []string `yaml:"start_time,omitempty"`

	// EndTime contains keywords to identify end time fields
	// Default: ["end time", "结束时间"]
	EndTime []string `yaml:"end_time,omitempty"`

	// Description contains keywords to identify description fields
	// Default: ["申请说明", "access resource description", "reason"]
	Description []string `yaml:"description,omitempty"`

	// CloudDetection contains keywords to detect cloud platform type from form fields
	// Key is the cloud type (gcp, azure, alibaba), value is keyword list
	// Default: gcp=["gcp account", "gcp project"], azure=["azure account", "azure subscription"], alibaba=["alibaba account", "阿里云"]
	CloudDetection map[string][]string `yaml:"cloud_detection,omitempty"`

	// SSOTypeKeywords contains keywords to identify if an application is SSO type
	// Default: ["sso", "生产账号申请", "production account application"]
	SSOTypeKeywords []string `yaml:"sso_type_keywords,omitempty"`

	// DefaultCloudType is the cloud type to use when no specific cloud is detected
	// Default: "AWS"
	DefaultCloudType string `yaml:"default_cloud_type,omitempty"`

	// DateFormats contains custom date format strings for parsing time fields
	// If not specified, built-in formats are used (RFC3339, ISO 8601, etc.)
	DateFormats []string `yaml:"date_formats,omitempty"`
}

// DatabaseConfig contains MySQL database connection configuration.
//
// Requirements: 2.4
type DatabaseConfig struct {
	// Host is the database server hostname
	// Default: 127.0.0.1
	Host string `yaml:"host" default:"127.0.0.1"`

	// Port is the database server port
	// Default: 3306
	Port int `yaml:"port" default:"3306"`

	// User is the database username
	// Can be overridden by DB_USER environment variable
	User string `yaml:"user" env:"DB_USER"`

	// Password is the database password
	// Can be overridden by DB_PASSWORD environment variable
	Password string `yaml:"password" env:"DB_PASSWORD"`

	// Database is the database name
	// Default: security
	Database string `yaml:"database" default:"security"`

	// MaxOpenConns is the maximum number of open connections to the database
	// Default: 10
	MaxOpenConns int `yaml:"max_open_conns" default:"10"`

	// MaxIdleConns is the maximum number of idle connections in the pool
	// Default: 5
	MaxIdleConns int `yaml:"max_idle_conns" default:"5"`

	// MaxLifetime is the maximum lifetime of a connection
	// Default: 1h
	MaxLifetime time.Duration `yaml:"max_lifetime" default:"1h"`
}

// ProvidersConfig contains configuration for all cloud platform providers.
//
// Requirements: 2.2, 2.3, 2.5, 2.6, 2.7
type ProvidersConfig struct {
	// AWS contains AWS SSO configuration
	AWS AWSConfig `yaml:"aws"`

	// GCP contains Google Cloud Platform configuration
	GCP GCPConfig `yaml:"gcp"`

	// Azure contains Microsoft Azure configuration
	Azure AzureConfig `yaml:"azure"`

	// Alibaba contains Alibaba Cloud configuration
	Alibaba AlibabaConfig `yaml:"alibaba"`
}

// AWSConfig contains AWS SSO (IAM Identity Center) configuration.
//
// Requirements: 2.5, 2.6
type AWSConfig struct {
	// IdentityCenterARN is the ARN of the IAM Identity Center instance
	IdentityCenterARN string `yaml:"identity_center_arn"`

	// IdentityStoreID is the ID of the Identity Store
	IdentityStoreID string `yaml:"identity_store_id"`

	// Region is the AWS region for SSO operations
	// Default: ap-northeast-1
	Region string `yaml:"region" default:"ap-northeast-1"`

	// Accounts is the list of AWS accounts managed by this system
	Accounts []CloudAccount `yaml:"accounts"`
}

// GCPConfig contains Google Cloud Platform configuration.
//
// Requirements: 2.6, 2.7
type GCPConfig struct {
	// CredentialsFile is the path to the GCP service account JSON file
	CredentialsFile string `yaml:"credentials_file"`

	// RoleMappingFile is the path to the GCP role mapping INI file
	RoleMappingFile string `yaml:"role_mapping_file"`

	// Projects is the list of GCP projects managed by this system
	Projects []CloudAccount `yaml:"projects"`
}

// AzureConfig contains Microsoft Azure configuration.
//
// Requirements: 2.2, 2.6
type AzureConfig struct {
	// TenantID is the Azure AD tenant ID
	// Can be overridden by AZURE_TENANT_ID environment variable
	TenantID string `yaml:"tenant_id" env:"AZURE_TENANT_ID"`

	// ClientID is the Azure AD application (client) ID
	// Can be overridden by AZURE_CLIENT_ID environment variable
	ClientID string `yaml:"client_id" env:"AZURE_CLIENT_ID"`

	// ClientSecret is the Azure AD application client secret
	// Can be overridden by AZURE_CLIENT_SECRET environment variable
	ClientSecret string `yaml:"client_secret" env:"AZURE_CLIENT_SECRET"`

	// Subscriptions is the list of Azure subscriptions managed by this system
	Subscriptions []CloudAccount `yaml:"subscriptions"`
}

// AlibabaConfig contains Alibaba Cloud configuration.
//
// Requirements: 2.3, 2.6
type AlibabaConfig struct {
	// AuthType specifies the authentication type
	// Supported values: "ecs_ram_role", "oidc_role_arn", "ram_role_arn"
	// Default: ecs_ram_role
	AuthType string `yaml:"auth_type,omitempty" default:"ecs_ram_role"`



	// RoleName is the RAM role name (for ecs_ram_role auth type)
	// When running on ECS, the instance can assume this role automatically
	RoleName string `yaml:"role_name"`

	// RoleArn is the RAM role ARN (for ram_role_arn or oidc_role_arn auth type)
	// Format: acs:ram::account-id:role/role-name
	RoleArn string `yaml:"role_arn"`

	// RoleSessionName is the session name for role assumption
	// Used with ram_role_arn or oidc_role_arn auth types
	RoleSessionName string `yaml:"role_session_name" default:"autosso-session"`

	// OIDCProviderArn is the OIDC provider ARN (for oidc_role_arn auth type)
	// Format: acs:ram::account-id:oidc-provider/provider-name
	OIDCProviderArn string `yaml:"oidc_provider_arn"`

	// OIDCTokenFile is the path to the OIDC token file (for oidc_role_arn auth type)
	// Used in Kubernetes environments with service account tokens
	OIDCTokenFile string `yaml:"oidc_token_file"`

	// DirectoryID is the Cloud SSO directory ID
	DirectoryID string `yaml:"directory_id"`

	// Endpoint is the Cloud SSO API endpoint
	// Default: cloudsso.cn-shanghai.aliyuncs.com
	Endpoint string `yaml:"endpoint" default:"cloudsso.cn-shanghai.aliyuncs.com"`

	// Accounts is the list of Alibaba Cloud accounts managed by this system
	Accounts []CloudAccount `yaml:"accounts"`
}

// CloudAccount represents a cloud account/project/subscription configuration.
// This is a unified structure used across all cloud providers.
//
// Requirements: 2.6
type CloudAccount struct {
	// ID is the unique identifier of the cloud account
	// For AWS: Account ID (e.g., "557537366020")
	// For GCP: Project ID (e.g., "tidbcloud-prod-000")
	// For Azure: Subscription ID (e.g., "ad881159-0593-4502-96e4-e2698b790a3d")
	// For Alibaba: Account ID (e.g., "5480039859161595")
	ID string `yaml:"id"`

	// Name is the human-readable name of the account
	Name string `yaml:"name"`

	// Type indicates the account type (e.g., "prod", "test", "dev")
	Type string `yaml:"type"`

	// RoleSuffix is used for Azure role name suffix mapping
	// This is specific to Azure subscriptions
	RoleSuffix string `yaml:"role_suffix,omitempty"`
}

// RuntimeConfig contains runtime behavior configuration.
//
// Requirements: 9.4
type RuntimeConfig struct {
	// PollInterval is the interval for polling new approval instances
	// Default: 5s
	PollInterval time.Duration `yaml:"poll_interval" default:"5s"`

	// ExpireCheckInterval is the interval for checking expired permissions
	// Default: 1h
	ExpireCheckInterval time.Duration `yaml:"expire_check_interval" default:"1h"`

	// GracePeriodDays is the number of days to wait before revoking expired permissions
	// Default: 3
	GracePeriodDays int `yaml:"grace_period_days" default:"3"`

	// HTTPTimeout is the timeout for HTTP requests
	// Default: 10s
	HTTPTimeout time.Duration `yaml:"http_timeout" default:"10s"`

	// MaxRetries is the maximum number of retry attempts for failed operations
	// Default: 3
	MaxRetries int `yaml:"max_retries" default:"3"`

	// LogLevel is the logging level (debug, info, warn, error)
	// Default: info
	LogLevel string `yaml:"log_level" default:"info"`

	// WhitelistEmails is the list of email addresses that should not have
	// their permissions automatically revoked
	WhitelistEmails []string `yaml:"whitelist_emails"`

	// GeneralPermissionSets is the list of permission sets that are considered general.
	// Non-general permission sets are tracked separately in statistics.
	// Used for AWS permissions.
	GeneralPermissionSets []string `yaml:"general_permission_sets"`

	// SkipHistoricalApprovals when true, only processes approvals created after program startup.
	// Historical approvals (created before startup) will be ignored.
	// Default: false
	SkipHistoricalApprovals bool `yaml:"skip_historical_approvals" default:"false"`
}

// PermissionMapping defines the mapping between Feishu permission names
// and actual cloud platform permission/role names.
//
// Requirements: 9.6
type PermissionMapping struct {
	// FeishuName is the permission name as shown in Feishu approval forms
	FeishuName string `yaml:"feishu_name"`

	// RealName is the actual permission/role name in the cloud platform
	RealName string `yaml:"real_name"`
}

// GCPRoleMapping defines the mapping between custom role names
// and actual GCP IAM roles. Each custom role can map to multiple GCP roles.
// This replaces the gcp_custom_role.ini file configuration.
//
// Requirements: 9.6, 10.4
type GCPRoleMapping struct {
	// CustomRole is the custom role name used in Feishu approval forms
	CustomRole string `yaml:"custom_role"`

	// GCPRoles is the list of actual GCP IAM roles to assign
	GCPRoles []string `yaml:"gcp_roles"`
}
