package config

import (
	"github.com/tidbcloud/account/pkg/ratecontroller/types"
)

var globalConf *CentralConfig = &CentralConfig{}

type CentralConfig struct {
	ServerConfig          ServerConfig         `mapstructure:"server"`
	GrpcConfig            GrpcConfig           `mapstructure:"grpc"`
	MysqlConfig           MysqlConfig          `mapstructure:"mysql"`
	BillingConfig         BillingConfig        `mapstructure:"billing"`
	Auth0Config           Auth0Config          `mapstructure:"auth0"`
	ZendeskConfig         ZendeskConfig        `mapstructure:"zendesk"`
	SalesforceConfig      SalesforceConfig     `mapstructure:"salesforce"`
	GrafanaConfig         GrafanaConfig        `mapstructure:"grafana"`
	RateControlConfig     RateControlConfig    `mapstructure:"rateControl"`
	MarketPlaceConfig     MarketPlaceConfig    `mapstructure:"marketPlace"`
	JobQueueConfig        JobQueueConfig       `mapstructure:"jobQueue"`
	OktaMapperConfig      map[string]uint64    `mapstructure:"oktaMapper"`
	OpenAPIGatewayConfig  OpenAPIGatewayConfig `mapstructure:"openapi"`
	PocApplicationWebhook string               `mapstructure:"pocApplicationWebhook"`
	DynamodbConfig        DynamodbConfig       `mapstructure:"dynamodb"`
	SSOConfig             SSOConfig            `mapstructure:"sso"`
	JsmConfig             JsmConfig            `mapstructure:"jsm"`
	ClusterProxyConfig    ClusterProxyConfig   `mapstructure:"proxy"`
	MspLogoConfig         MspLogoConfig        `mapstructure:"mspLogo"`
	RedisConfig           RedisConfig          `mapstructure:"redis"`
}

type RedisConfig struct {
	RedisHost string `mapstructure:"redisHost" required:"true" default:"platform-dev.v5szfq.ng.0001.usw2.cache.amazonaws.com:6379"`
	RedisDB   int    `mapstructure:"redisDB" required:"true" default:"4"`
}

type JsmConfig struct {
	Enable         bool   `mapstructure:"enable" required:"true" default:"false"`
	Domain         string `mapstructure:"domain" required:"true"`
	User           string `mapstructure:"user" required:"true" default:"tidbsupport@pingcap.com"`
	ApiToken       string `mapstructure:"apiToken" required:"true"`
	RequestTypeId  string `mapstructure:"requestTypeId" required:"true" default:"30"`
	ServiceDeskId  string `mapstructure:"serviceDeskId" required:"true" default:"6"`
	CustomerGroup  string `mapstructure:"CustomerGroup" required:"true" default:"jira-servicemanagement-customers-pingcap-ticket-sandbox-313"`
	JobQueueRegion string `mapstructure:"jobQueueRegion" required:"true" default:"us-west-2"`
	JobQueueUrl    string `mapstructure:"jobQueueUrl" required:"true"`
}

type ClusterProxyConfig struct {
	Auth0Domain       string `mapstructure:"auth0Domain"`
	Auth0ClientID     string `mapstructure:"auth0ClientID"`
	Auth0ClientSecret string `mapstructure:"auth0ClientSecret"`
	Auth0Audience     string `mapstructure:"auth0Audience"`
}
type MspLogoConfig struct {
	MspCloudfrontDomain   string `mapstructure:"mspCloudfrontDomain"`
	MspCloudfrontS3bucket string `mapstructure:"mspCloudfrontS3bucket"`
}

type SSOConfig struct {
	Auth0Domain         string `mapstructure:"auth0Domain" required:"true"`
	M2mAppClientID      string `mapstructure:"m2mAppClientID" required:"true"`
	M2mAppClientSecret  string `mapstructure:"m2mAppClientSecret" required:"true"`
	EnableClients       string `mapstructure:"enableClients" required:"true"`
	ActionKey           string `mapstructure:"actionKey" required:"true"`
	ClaimIss            string `mapstructure:"claimIss" required:"true"`
	Auth0Tenant         string `mapstructure:"auth0Tenant" required:"true"`
	IamOpenApiDomain    string `mapstructure:"iamOpenApiDomain" required:"true"`
	Auth0CallbackDomain string `mapstructure:"auth0CallbackDomain" required:"true"`
}

type GrpcConfig struct {
	CorePortalAddr  string `mapstructure:"corePortalAddr" default:"dbaas-core-portal-server-grpc:10000"`
	CoreSvcAddr     string `mapstructure:"coreSvcAddr" default:"dbaas-core-svc-server-grpc:8888"`
	DataflowSvcAddr string `mapstructure:"dataflowSvcAddr" default:"dataflow-grpc:10000"`
	AclSvcAddr      string `mapstructure:"aclSvcAddr" default:"account-acl-grpc:10000"`
	AccountSvcAddr  string `mapstructure:"accountSvcAddr" default:"account-provider-grpc:10000"`
	DataAPISvcAddr  string `mapstructure:"dataAPISvcAddr" default:"dataservice-dataapi-service:10000"`
	DevopsSvcAddr   string `mapstructure:"devopsSvcAddr" default:"devops-server-grpc.devops:8089"`
	IPAPISvcAddr    string `mapstructure:"ipAPISvcAddr" default:"ipip-svc:8080"`
	AuthServerAddr  string `mapstructure:"authServerAddr" default:"authserver-provider-service:10000"`
	CleanClusterKey string `mapstructure:"cleanClusterKey"`
	MgmtSvcAddr     string `mapstructure:"mgmtSvcAddr" default:"tidb-mgmt-service.tidb-management-service:10001"`
}

type MarketPlaceConfig struct {
	EnableBackground bool `mapstructure:"marketplaceBackground"`

	AWSProductCode string `mapstructure:"awsProductCode" default:"9nm2jrkj099y2y0ahwbfhv60l"`

	AWSCPPODiscountableProductCode    string `mapstructure:"awsCPPODiscountableProductCode" default:"e67152a3ts3l542poaxiwzmld"`
	AWSCPPONonDiscountableProductCode string `mapstructure:"awsCPPONonDiscountableProductCode" default:"bbxqe8gfofwxugknh14ohu6m5"`

	AWSRole             string `mapstructure:"awsRole"`
	AWSSQS              string `mapstructure:"awsSQS"`
	AWSCPPOSQS          string `mapstructure:"awsCPPOSQS" default:"https://sqs.us-west-2.amazonaws.com/470438934515/tidbcloud-cppo-products-notification-dev"`
	AWSUserEventSQS     string `mapstructure:"awsUserEventSQS"`
	EnableAwsBackground bool   `mapstructure:"awsBackground"`

	GCPProductCode        string `mapstructure:"gcpProductCode"`
	GCPProject            string `mapstructure:"gcpProject"`
	GCPISSURL             string `mapstructure:"gcpISSURL" default:"https://www.googleapis.com/robot/v1/metadata/x509/cloud-commerce-partner@system.gserviceaccount.com"`
	GCPProcurementBaseUrl string `mapstructure:"gcpProcurementBaseUrl" default:"https://cloudcommerceprocurement.googleapis.com/"`
	GCPPubSubTopic        string `mapstructure:"gcpPubSubTopic"`
	GCPMarketPlaceSA      string `mapstructure:"gcpMarketplaceSA"`
	EnableGCPBackground   bool   `mapstructure:"gcpBackground"`

	AliMNSEndpoint  string `mapstructure:"aliMNSEndpoint"`
	AliAccessKey    string `mapstructure:"aliAccessKey"`
	AliSecretKey    string `mapstructure:"aliSecretKey"`
	AliIsvKey       string `mapstructure:"aliIsvKey"`
	AliIsvKeyStr    string `mapstructure:"aliIsvKeyStr"`
	AliMNSQueueName string `mapstructure:"aliMNSQueueName"`
}

type RateControlConfigItem struct {
	Scene *types.Scene  `mapstructure:"scene"`
	Rates []*types.Rate `mapstructure:"rates"`
}

type RateControlConfig struct {
	InviteUser               RateControlConfigItem `mapstructure:"inviteUser"`
	RegistrationVerification RateControlConfigItem `mapstructure:"registrationVerification"`
	SendPasswordVerifyCode   RateControlConfigItem `mapstructure:"sendPasswordVerifyCode"`
	Registration             RateControlConfigItem `mapstructure:"registration"`
}

type ServerConfig struct {
	// Log level: debug, info, warn, error, fatal
	LogLevel         string `mapstructure:"logLevel" default:"info" validate:"oneof=debug info warn error fatal"`
	EnableDBQueryLog bool   `mapstructure:"enableDBQueryLog" default:"false"`

	FrontendDNS          string `mapstructure:"frontendDNS" validate:"required"`
	AlicloudSignUpDomain string `mapstructure:"alicloudSignUpDomain" validate:"required" default:"dev.console.tidb.io"`
	BackendDNS           string `mapstructure:"backendDNS" validate:"required"`

	// If EnableEmailProviderBlocklists is true, user cannot register using the email address suffix in the dbbas.email_provider_blocklists table
	EnableEmailProviderBlocklists bool `mapstructure:"enableEmailProviderBlocklists" default:"false"`

	Stage    string `mapstructure:"stage" validate:"required"`
	GrpcPort int    `mapstructure:"grpcPort" default:"10000"`
	// open api grpc server start port
	OpenApiGrpcPort int `mapstructure:"openApiGrpcPort" default:"11010"`
	//the central metrics port
	MetricsPort uint16 `mapstructure:"metricsPort" default:"9090"`
	// session secret salt conf
	SaltSecret string `mapstructure:"saltSecret" required:"true"`
	// mailgun conf
	MailGunApiKey string `mapstructure:"mailGunApiKey" required:"true"`
	// sendgrid conf
	SendgridApiKey string `mapstructure:"sendgridApiKey" required:"true"`

	EnableRecaptcha bool `mapstructure:"enableRecaptcha" default:"false"`

	// recaptcha secret conf
	RecaptchaSecret string `mapstructure:"recaptchaSecret" required:"true"`

	SentryConf SentryConfig `mapstructure:"sentry"`

	SecretStore *SecretConfig `mapstructure:"secret"`

	PocManualBackupReservedDays *int `mapstructure:"pocManualBackupReservedDays" validate:"required"`

	ManagementPortalInitUserEmail *string `mapstructure:"managementPortalInitUserEmail" default:"cloud@pingcap.com"`

	// BizOpsTeamEmail is the email of business ops team
	BizOpsTeamEmail string `mapstructure:"bizOpsTeamEmail"`

	// listen addr
	AdminListenAddr   string `mapstructure:"adminListenAddr" default:"0.0.0.0:8080"`
	MetricsListenAddr string `mapstructure:"metricsListenAddr" default:"0.0.0.0:8080"`

	// thanos addr
	ThanosAddr string `mapstructure:"thanosAddr" default:"http://thanos-query.monitoring:9090"`

	// whitelist for functions cdc to mysql and cdc to kafka
	EnableDataStreamToMysql []uint64 `mapstructure:"enableDataStreamToMysql"`
	EnableDataStreamToKafka []uint64 `mapstructure:"enableDataStreamToKafka"`
	EnableReplication       []uint64 `mapstructure:"enableReplication"`
	EnableAuditLog          []uint64 `mapstructure:"enableAuditLog"`
	EnableXAccount          []uint64 `mapstructure:"enableXAccount"`
	// XXX(bing.wang) Relased to public
	// EnableOpenAPI           []uint64 `mapstructure:"enableOpenAPI"`
	EnableNewClusterListUI []uint64 `mapstructure:"enableNewClusterListUI"`

	// check if loaded remote config
	RemoteConfigEnabled bool `mapstructure:"remoteConfigEnabled"`

	CDNBucketPathPrefix string `mapstructure:"cdnBucketPathPrefix" default:"uploaded"`
	EnableCDNBucket     bool   `mapstructure:"enableCDNBucket" default:"true"`
	CDNBucket           string `mapstructure:"cdnBucket"`
	CDNFileContentType  string `mapstructure:"cdnFileContentType" default:"application/octet-stream"`

	StressTest bool `mapstructure:"stressTest" default:"false"`
}

type SentryConfig struct {
	DSN         string `mapstructure:"dsn"`
	Environment string `mapstructure:"env"`
	LogLevel    string `mapstructure:"logLevel" default:"warn"`
}

type SecretConfig struct {
	SecretKey string `mapstructure:"secretKey"`
	Region    string `mapstructure:"region"`
}

type GrafanaConfig struct {
	Server           string `mapstructure:"server"  default:"https://grafana.oauth.dev.shared.aws.tidbcloud.com/"`
	APIKey           string `mapstructure:"apiKey"`
	TidbDashboardTag string `mapstructure:"tidbDashboardTag" default:"tidb-mixin"`
}

type ZendeskConfig struct {
	EnableZendesk   bool   `mapstructure:"enableZendesk" default:"false"`
	ZendeskEmail    string `mapstructure:"zendeskEmail"`
	ZendeskDomain   string `mapstructure:"zendeskDomain"`
	ZendeskAPIToken string `mapstructure:"zendeskAPIToken"`
	ZendeskSecret   string `mapstructure:"zendeskSecret"`
}

type SalesforceConfig struct {
	EnableSalesforce       bool   `mapstructure:"enableSalesforce" default:"false"`
	SalesforceDomain       string `mapstructure:"salesforceDomain"`
	SalesforceClientID     string `mapstructure:"salesforceClientID"`
	SalesforceClientSecret string `mapstructure:"salesforceClientSecret"`
	SalesforceUsername     string `mapstructure:"salesforceUsername"`
	SalesforcePassword     string `mapstructure:"salesforcePassword"`
}

type Auth0Config struct {
	Auth0ManagementClientID     string `mapstructure:"auth0ManagementClientID" required:"true"`
	Auth0ManagementClientSecret string `mapstructure:"auth0ManagementClientSecret" required:"true"`
	Auth0DatabaseConnectionName string `mapstructure:"auth0DatabaseConnectionName" required:"true" default:"custom-email"`

	Auth0Domain   string `mapstructure:"auth0Domain" required:"true"`
	Auth0Audience string `mapstructure:"auth0Audience" required:"true"`
	Auth0Secret   string `mapstructure:"auth0Secret" required:"true"`

	ManagementPortalAuth0Domain         string `mapstructure:"managementPortalAuth0Domain" required:"true"`
	ManagementPortalAuth0Audience       string `mapstructure:"managementPortalAuth0Audience" required:"true"`
	ManagementPortalAuth0Secret         string `mapstructure:"managementPortalAuth0Secret" required:"true"`
	ManagementPortalAuth0ClientAudience string `mapstructure:"managementPortalAuth0ClientAudience" required:"true"`
}

type BillingConfig struct {
	// The billing system base url
	Billing2BaseURL       string            `mapstructure:"billing2BaseURL" default:"http://billing2-api:18888" required:"true"`
	Billing2URLPrefix     string            `mapstructure:"billing2URLPrefix" default:"/api/v1/billing" required:"true"`
	BillingPackageIDs     BillingPackageIDs `mapstructure:"billingPackageIDs"`
	EnablePOCEndedCleanup bool              `mapstructure:"enablePOCEndedCleanup" default:"true"`
	EnableCDCTCUMetering  bool              `mapstructure:"enableCDCTCUMetering" default:"false"`
	CDCTCUMappingTable    [][]int           `mapstructure:"cdcTCUMappingTable" default:"[[0,16], [48,24], [120,32], [169, 40]]"`
	DiscountDescription   string            `mapstructure:"discountDescription" default:""`
	POCCleanupRefreshDays int               `mapstructure:"POCCleanupRefreshDays" default:"14"`
	POCClusterRemainDays  int               `mapstructure:"POCClusterRemainDays" default:"3"`
	AliCloudManagerOrgID  uint64            `mapstructure:"AliCloudManagerOrgID" default:"0"`
}

type BillingPackageIDs struct {
	OnDemand uint64 `mapstructure:"onDemand"`
	Poc      uint64 `mapstructure:"poc"`
	DevTier  uint64 `mapstructure:"devTier"`
}

type MysqlConfig struct {
	Host                     string `mapstructure:"host" default:"host"`
	User                     string `mapstructure:"user" default:"root"`
	Port                     uint16 `mapstructure:"port" default:"4000"`
	Password                 string `mapstructure:"password" required:"true"`
	Database                 string `mapstructure:"database" default:"dbaas"`
	MaxOpenConns             int    `mapstructure:"maxOpenConns" default:"1000"`
	DisableNestedTransaction bool   `mapstructure:"disableNestedTransaction" default:"true"`
	SecondUser               string `mapstructure:"second_user"`
	SecondUserPassword       string `mapstructure:"second_user_password"`
}

type JobQueueConfig struct {
	JobQueueURL     string `mapstructure:"jobQueueURL"`
	JobQueueDLURL   string `mapstructure:"jobQueueDLURL"` // dead letter
	JobQueueRegion  string `mapstructure:"jobQueueRegion"`
	JobQueueTimeout int64  `mapstructure:"jobQueueTimeout" default:"300"`
}

type OpenAPIGatewayConfig struct {
	OpenAPIGatewayRedisPassword         string   `mapstructure:"openapiGatewayRedisPassword"`
	OpenAPIGatewayRedisMasterAddress    string   `mapstructure:"openapiGatewayRedisMasterAddress"`
	OpenAPIGatewayRedisReplicaAddresses []string `mapstructure:"openapiGatewayRedisReplicaAddresses"`
	OpenAPISecretKey                    string   `mapstructure:"openapiSecretKey"`
	OpenAPISecretIv                     string   `mapstructure:"openapiSecretIv"`
	EnableGatewayAuth                   bool     `mapstructure:"enableGatewayAuth"`
}

type DynamodbConfig struct {
	Region                 string `mapstructure:"region"`
	ApiKeyTableName        string `mapstructure:"apiKeyTableName"`
	PrivilegeRoleTableName string `mapstructure:"privilegeRoleTableName"`
	PrivilegeRoleGSIName   string `mapstructure:"privilegeRoleGSIName"`
	DisableWrite           bool   `mapstructure:"disableWrite" default:"false"`
}

//type RbacConfig struct {
//	Systems string `mapstructure:"Systems"`
//}
