package config

import (
	"time"
)

const (
	// ClusterPrefix is the prefix for k8s resources
	ClusterPrefix = "db"
	// LocalOperatorNamespace is the namespace to run local operation components of dbaas
	LocalOperatorNamespace = "tidb-admin"
	// LocalProxyName is the local proxy in shoot cluster
	LocalProxyName = "dbaas-proxy"

	// TestE2EUser test e2e user is the user of e2e test
	TestE2EUser = "teste2e@pingcap.com"

	// TimeFormat is the time format for generate backup name
	TimeFormat = "2006-01-02t15-04-05"

	TimeFmtDTM = "2006-01-02 15:04:05"

	// SystemEmail is the email used for autonomous operations
	SystemEmail = "system@pingcap.com"

	DefaultUtcOffset    = "0"
	DefaultTidbQuota    = 20
	DefaultTikvQuota    = 30
	DefaultTiflashQuota = 30
	DefaultProjectName  = "default project"

	FinalBackupName                = "final-backup"
	MaxAutoBackups          uint64 = 7
	DefaultAutoBackupHour          = 2
	DevTierMaxAutoBackups   uint64 = 1
	DevTierMaxManualBackups uint64 = 2
	MaxFreeClusterCount            = 1

	RegistrationSourceEmail   = "custom-email"
	PortalAuthorizationHeader = "Portal-Authorization"
	AuthorizationHeader       = "Authorization"
	SalesforceApiKeyName      = "salesforce"
	ProfileMngApiKeyName      = "profile_mng"

	// Deployment stage
	StageProd    = "prod"
	StageStaging = "staging"

	Duration4DevTierTrialStageNormal   = Duration4DevTierTrialTotal - Duration4DevTierCloseToEndStage1
	Duration4DevTierCloseToEndStage1   = 14 * time.Hour * 24  // two week before trial end
	Duration4DevTierCloseToEndStage2   = 2 * time.Hour * 24   // two day before trial end
	Duration4DevTierTrialTotal         = 365 * time.Hour * 24 // total duration of dev tier trial
	Duration4DevTierIdleStageEncourage = 2 * time.Hour * 24
	Duration4DevTierIdleStageWarning   = 6 * time.Hour * 24
	Duration4DevTierIdleStageShutdown  = 7 * time.Hour * 24
	MaxTrafficUsagePerWeek4DevTier     = 20 * 1024 * 1024 * 1024 // 20GB
	ThrottledDevTierBandwidth          = "10KiB/s"
	DevTierImportStorageRequest        = "100Gi"

	DefaultDBOperationTimeout = 30 * time.Second

	// Replication constrant
	ReplicationDefaultReplicas = 3

	// Max metrics key count
	MaxMetricsKeyCount = 10

	GetClusterTsoClase            = "SHOW MASTER STATUS;"
	GetGCLifeTimeClause           = "SELECT VARIABLE_VALUE FROM mysql.tidb WHERE VARIABLE_NAME = 'tikv_gc_life_time';"
	SetGCLifeTimeClause           = "SET GLOBAL TIDB_GC_LIFE_TIME='%s';"
	SetRestrictReadonlyClause     = "SET GLOBAL TIDB_RESTRICTED_READ_ONLY='%s'"
	SetSuperReadonlyClause        = "SET GLOBAL TIDB_SUPER_READ_ONLY='%s'"
	GetAuditLogStatusClause       = "SHOW GLOBAL VARIABLES WHERE VARIABLE_NAME = 'tidb_audit_redact_log'"
	SetAuditLogRedactStatusClause = "SET @@GLOBAL.tidb_audit_redact_log = %s"
	SetAuditLogMaxSize            = "SET @@GLOBAL.tidb_audit_log_max_size = 10485760"
	EnableAuditPluginClause       = "admin plugins enable audit"
	DisableAuditPluginClause      = "admin plugins disable audit"
	GetAllAuditLogAccessClause    = "SELECT id, user, db, tbl, access_type FROM mysql.tidb_audit_table_access ORDER BY id"
	DeleteAuditLogAccessClause    = "DELETE FROM mysql.tidb_audit_table_access WHERE id=%d"
	CreateAuditLogAccessClause    = "INSERT INTO mysql.tidb_audit_table_access (`user`, `db`, `tbl`, `access_type`, `create_time`) VALUES ('%s', '%s', '%s', '%s', NOW())"
	FlushAuditLogAccessClause     = "FLUSH tidb plugins audit"
	ReplicationGcLifeTime         = "72h"
	PhysicalShiftBits             = 18

	// audit log
	AuditRedactLogStatusON  = "ON"
	AuditRedactLogStatusOFF = "OFF"

	// cluster proxy
	DefaultClusterProxyTimeout  = 8
	AuditLogClusterproxyTimeout = 30

	// cluster tier
	RecommendedNodeCpuNum = 8
)

const (
	ErrCreateVPCPeeringPrerequisite = "You should create at least one non-free tier cluster in that region before creating a VPC Peering."
	ErrAtLeastOneOwner              = "The organization needs to have at least one owner."
	ErrDeleteProject                = "The project has a running cluster. Before deleting the project, all clusters need to be deleted."
	ErrImpersonatedUser             = "impersonated user is a read only user"
	ErrProjectCIDRExist             = "Project CIDR already exist"
)

// UserVisibleClusterComponents lists the proto component type names that are user-visible.
// These correspond to the ComponentType field values in TargetCluster.Components.
var (
	UserVisibleClusterComponents = []string{
		"COMPONENT_TYPE_TIDB",
		"COMPONENT_TYPE_TIKV",
		"COMPONENT_TYPE_TIFLASH",
	}
	CreatingClusterStatusSet = map[string]bool{
		"CLUSTER_STATUS_INITIALIZING": true,
		"CLUSTER_STATUS_PREPARING":    true,
		"CLUSTER_STATUS_LAUNCHING":    true,
	}
)

func UserVisibleClusterComponentsContains(c string) bool {
	for _, v := range UserVisibleClusterComponents {
		if v == c {
			return true
		}
	}
	return false
}

var (
	// audit log
	ValidAuditLogAccessTypeOption = map[string]bool{
		"AlterTable":        true,
		"AnalyzeTable":      true,
		"Begin":             true,
		"Change":            true,
		"Commit":            true,
		"CreateDatabase":    true,
		"CreateIndex":       true,
		"CreateTable":       true,
		"CreateView":        true,
		"CreateUser":        true,
		"Delete":            true,
		"DropDatabase":      true,
		"DropIndex":         true,
		"DropView":          true,
		"DropTable":         true,
		"DescTable":         true,
		"ExplainAnalyzeSQL": true,
		"ExplainSQL":        true,
		"Replace":           true,
		"Insert":            true,
		"LoadData":          true,
		"RollBack":          true,
		"Select":            true,
		"Set":               true,
		"Show":              true,
		"TruncateTable":     true,
		"Update":            true,
		"Grant":             true,
		"Revoke":            true,
		"Deallocate":        true,
		"Execute":           true,
		"Prepare":           true,
		"Use":               true,
		"CreateBinding":     true,
		"IndexAdvise":       true,
		"DropBinding":       true,
		"Trace":             true,
		"Shutdown":          true,
		"other":             true,
	}
)
