package precheckcatalog

import "github.com/tidbcloud/tidb-management-service/tidb-mgmt-service/domain/entity"

type Check struct {
	Key   string
	Title string
	Why   string
}

var FeatureGapChecks = []Check{
	{
		Key: "customer_private_endpoint", Title: "Private endpoint",
		Why: "Premium uses newly created private endpoints for the target instance by default. " +
			"Applications using Dedicated private endpoints must switch to the new Premium private endpoints. " +
			"Note: Seamless endpoint switch is a potential solution for customers who cannot update applications due to additional manual effort.",
	},
	{
		Key: "vpc_peering", Title: "VPC peering",
		Why: "Premium does not support VPC peering. " +
			"Customers using Dedicated VPC peering must switch to Premium private endpoint connectivity.",
	},
	{
		Key: "public_endpoint", Title: "Public endpoint",
		Why: "Premium uses a different public endpoint from Dedicated. " +
			"Applications using the Dedicated public endpoint must update connection configuration after migration.",
	},
	{
		Key: "sql_port", Title: "Custom port",
		Why: "Premium uses SQL port 4000 by default. " +
			"If the Dedicated cluster uses a custom SQL port, application connection configuration must be updated during migration.",
	},
	{
		Key: "project_rbac", Title: "Project / RBAC",
		Why: "Migration execution requires sufficient permissions to create the target Premium instance and perform migration operations. " +
			"The migration account should be Org owner, Project Owner or Instance Manager.",
	},
	{
		Key: "cmek", Title: "CMEK",
		Why: "If Dedicated uses CMEK, the target Premium planning must include CMEK enablement and required KMS permissions " +
			"for restore tasks.",
	},
	{
		Key: "non_default_tidb_node_group", Title: "TiDB node groups",
		Why: "Premium does not support TiDB node groups. " +
			"Workload isolation that depends on TiDB node groups may need to be redesigned.",
	},
	{
		Key: "audit_log_v1", Title: "Database audit logging",
		Why: "Premium database audit logging is compatible with audit logging v2, but not with audit logging v1. " +
			"Customers using v1 may need to change their audit log consumption process.",
	},
	{
		Key: "changefeed_sink", Title: "Changefeed compatibility",
		Why: "Premium supports only specific changefeed downstream types. " +
			"Unsupported downstreams may require customer confirmation and an alternative CDC plan.",
	},
	{
		Key: "dedicated_api_usage", Title: "Dedicated API",
		Why: "Dedicated API and Premium API are not equivalent. Dedicated uses the v1beta1 API, for example " +
			"https://dedicated.tidbapi.com/v1beta1/clusters, while Premium uses the v1beta2 API, for example " +
			"https://cloud.tidbapi.com/v1beta2/tidbs. API endpoints, resource models, and automation workflows may change after migration. " +
			"If the customer uses Dedicated API for automation, existing scripts or integrations may fail after migrating to Premium.",
	},
	{
		Key: "resource_pool_plan", Title: "Resource pool",
		Why: "Shared or isolated resource pool choice may affect cost, capacity planning, operational isolation, and customer impact. " +
			"The decision should be made during migration planning with frontline, product, and engineering input.",
	},
}

var MigrationReadinessChecks = []Check{
	{
		Key: "duplicate_check_constraints", Title: "Duplicate check constraints",
		Why: "Duplicate check-constraint names within the same database can cause BR schema restore to fail. " +
			"The duplicates must be resolved before the migration backup is created.",
	},
	{
		Key: "mysql_db_collation_compatibility", Title: "mysql.db collation compatibility",
		Why: "BR restore will fail if there are privilege table compatibility risks.",
	},
	{
		Key: "invalid_foreign_key", Title: "Invalid foreign keys",
		Why: "Invalid foreign key can block schema restore. " +
			"These definitions must be identified and cleaned up before the migration backup is created.",
	},
	{Key: "tidb_version", Title: "TiDB version", Why: "Check TiCDC Compatibility."},
	{
		Key: "tidb_gc_life_time", Title: "TiDB GC life time",
		Why: "tidb_gc_life_time must cover the complete BR backup, BR restore, and TiCDC catch-up window. " +
			"Set it to at least 72h before the backup starts. If historical MVCC versions are garbage-collected before TiCDC finishes " +
			"catching up, the changefeed can enter an unrecoverable failed state. Recovery would require restarting the migration " +
			"from a new full backup.",
	},
	{
		Key: "tables_without_valid_index", Title: "Tables without a valid index",
		Why: "TiCDC only replicates tables that have at least one valid index to the downstream. " +
			"If an index in a table meets one of the following requirements, it is valid. A primary key (PRIMARY KEY) is a valid index. " +
			"A unique index (UNIQUE INDEX) is valid if every column of the index is explicitly defined as non-nullable (NOT NULL) " +
			"and the index does not have a virtual generated column (VIRTUAL GENERATED COLUMNS).",
	},
	{
		Key: "sequence", Title: "Sequences",
		Why: "TiCDC unsupported scenario: The CREATE SEQUENCE DDL operation and the SEQUENCE function in TiDB. " +
			"When the upstream TiDB uses SEQUENCE, TiCDC ignores SEQUENCE DDL operations/functions performed upstream. " +
			"However, DML operations using SEQUENCE functions can be correctly replicated.",
	},
	{
		Key: "new_collation_enabled", Title: "New collation enabled",
		Why: "A dedicated cluster with new_collation_enabled disabled does not currently support migration to a Premium cluster.",
	},
	{
		Key: "ttl", Title: "TTL",
		Why: "During migration, an Incremental Replication task is created to replicate changes from the Dedicated cluster to the Premium cluster. " +
			"To prevent duplicate TTL deletions, TTL_ENABLE is automatically set to OFF on the downstream tables, while TTL-triggered deletions " +
			"on the upstream cluster are replicated to the downstream cluster. After cutover, the customer must manually set TTL_ENABLE = 'ON' " +
			"on the Premium cluster for each table that has TTL configured. During rollback preparation, a reverse Incremental Replication task " +
			"is created to replicate changes from the Premium cluster back to the Dedicated cluster. To prevent TTL-triggered deletions from being " +
			"applied twice, the customer must disable TTL job execution on the Dedicated cluster before cutover.",
	},
	{Key: "tiflash_replicas", Title: "TiFlash replicas", Why: "Check TiFlash usage."},
}

func Find(category entity.PrecheckCategory, key string) (Check, bool) {
	var checks []Check
	switch category {
	case entity.PrecheckCategoryFeatureGap:
		checks = FeatureGapChecks
	case entity.PrecheckCategoryMigrationReadiness:
		checks = MigrationReadinessChecks
	default:
		return Check{}, false
	}
	for _, check := range checks {
		if check.Key == key {
			return check, true
		}
	}
	return Check{}, false
}

func NewItems() []*entity.DedicatedToPremiumPrecheckItem {
	items := make([]*entity.DedicatedToPremiumPrecheckItem, 0, len(FeatureGapChecks)+len(MigrationReadinessChecks))
	for i, check := range FeatureGapChecks {
		items = append(items, &entity.DedicatedToPremiumPrecheckItem{
			Category: entity.PrecheckCategoryFeatureGap, CheckKey: check.Key, Title: check.Title,
			Position: i, Why: check.Why, ExecutionState: entity.PrecheckItemExecutionStatePending,
		})
	}
	for i, check := range MigrationReadinessChecks {
		items = append(items, &entity.DedicatedToPremiumPrecheckItem{
			Category: entity.PrecheckCategoryMigrationReadiness, CheckKey: check.Key, Title: check.Title,
			Position: i, Why: check.Why, ExecutionState: entity.PrecheckItemExecutionStatePending,
		})
	}
	return items
}
