package common

import (
	"fmt"
	"strconv"
	"strings"

	globalngv1 "github.com/tidbcloud/tidb-management-service/api/spec/global/nextgen/v1"
	"github.com/tidbcloud/tidb-management-service/nextgen-global-service/domain/entity"
)

// Var keys
const (
	KeyRequest                              = "request"
	KeyClusterId                            = "cluster_id"
	KeyClusterDisplayName                   = "cluster_display_name"
	KeyTidbGroupId                          = "tidb_group_id"
	KeyTidbGroupIds                         = "tidb_group_ids" // separated by comma
	KeyResourcePoolId                       = "resource_pool_id"
	KeyTargetStatus                         = "target_status"
	KeyVpcId                                = "vpc_id"
	KeyCloudProviderName                    = "cloud_provider_name"
	KeyRegionLogicalName                    = "region_logical_name"
	KeyVpcPeeringId                         = "vpc_peering_id"
	KeyVpcPeeringConfig                     = "vpc_peering_config"
	KeyClusterApplyMask                     = "cluster_apply_mask" // apply cluster
	KeyNewCluster                           = "new_cluster"
	KeyEventName                            = "event_name"
	KeyClusterConfiguration                 = "cluster_configuration"
	KeySkipWaitAvailable                    = "skip_wait_available"
	KeyClusterPausePlan                     = "cluster_pause_plan"
	KeyPrivateLinkConnectionId              = "private_link_connection_id"
	KeyPrivateEndpointId                    = "private_endpoint_id"
	KeyPrivateLinkConnection                = "private_link_connection"
	KeyPrivateLbEnable                      = "private_lb_enable"
	KeyTidbGroupIdWithPrivateLinkServiceIds = "tidb_group_id_with_private_link_service_ids"
	KeyPrivateLinkServiceIds                = "private_link_service_ids"
	KeyPrivateLinkServiceId                 = "private_link_service_id"
	KeyAuditLogSettingId                    = "audit_log_setting_id"
	KeyAuditLogFilterRuleUserExpr           = "audit_log_filter_rule_user_expr"
	KeyAuditLogFilterRuleId                 = "audit_log_filter_rule_id"
	KeyTargetClusterId                      = "target_cluster_id"
	KeyDataplaneId                          = "dataplane_id"
	KeyEncryptionKeyId                      = "encryption_key_id"
	KeyExportId                             = "export_id"
	KeyEncryptionMode                       = "encryption_mode"
	KeyTargetMasterKey                      = "target_master_key"
	KeyTransitionType                       = "transition_type"
	KeyDnsIdentity                          = "dns_identity"
	KeyDisablePublicDnsIdentity             = "disable_public_dns_identity"
	KeyPreviousReservedCapacityTemplateId   = "previous_reserved_capacity_template_id"
	KeyReservedCapacityTemplateId           = "reserved_capacity_template_id"
	KeyOldMaxRcu                            = "old_max_rcu"
	KeyNewMaxRcu                            = "new_max_rcu"
)

// scale keys
const (
	ScaleTaskKeyRequestBody = "request_body"
	KeyOperationId          = "operation_id"
)

func GenerateTidbGroupIdWithPrivateLinkServiceIds(services []*entity.PrivateLinkService) string {
	ids := make([]string, 0, len(services))
	for _, service := range services {
		ids = append(ids, fmt.Sprintf("%d:%d", service.TidbGroupId, service.PrivateLinkServiceID))
	}
	return strings.Join(ids, ",")
}

func ParseTidbGroupIdWithPrivateLinkServiceIds(ids string) ([]*entity.PrivateLinkService, error) {
	services := make([]*entity.PrivateLinkService, 0, len(ids))
	for id := range strings.SplitSeq(ids, ",") {
		parts := strings.Split(id, ":")
		if len(parts) != 2 {
			return nil, fmt.Errorf("invalid id: %s", id)
		}
		tidbGroupId, err := strconv.ParseUint(parts[0], 10, 64)
		if err != nil {
			return nil, fmt.Errorf("invalid tidb group id: %s", parts[0])
		}
		privateLinkServiceId, err := strconv.ParseUint(parts[1], 10, 64)
		if err != nil {
			return nil, fmt.Errorf("invalid private link service id: %s", parts[1])
		}
		services = append(services, &entity.PrivateLinkService{
			PrivateLinkService: &globalngv1.PrivateLinkService{
				TidbGroupId: tidbGroupId,
			},
			PrivateLinkServiceID: privateLinkServiceId,
		})
	}
	return services, nil
}
