package aks

import (
	"fmt"
	"strings"

	"github.com/tidbcloud/infra-provider/pkg/namer"
	"github.com/tidbcloud/infra-provider/regional-server/api/v1alpha1"
	"github.com/tidbcloud/infra-provider/regional-server/pkg/controllers"
	taskcontext "github.com/tidbcloud/infra-provider/regional-server/pkg/controllers/appbox/task"
)

func getOIDCIssuerURLWithoutScheme(oidcurl string) string {
	return strings.TrimPrefix(oidcurl, "https://")
}

const userAssignedIdentityResourceIDFormat = "/subscriptions/%s/resourceGroups/%s/providers/Microsoft.ManagedIdentity/userAssignedIdentities/%s"

func aksClusterName(appBox *v1alpha1.APPBox) string {
	return namer.UniqueIdentifier(appBox.ObjectMeta, namer.WithLimit(AKSNameLimit))
}

func aksControlPlaneManagedIdentityName(appBox *v1alpha1.APPBox) string {
	return fmt.Sprintf("%s-cp-mi", aksClusterName(appBox))
}

func aksControlPlaneManagedIdentityResourceID(c *taskcontext.Context) (string, error) {
	if c == nil || c.VPC == nil || c.VPC.Spec.AccountRef == nil {
		return "", fmt.Errorf("azure account reference is required for AKS managed identity")
	}

	subscriptionID := strings.TrimSpace(c.VPC.Spec.AccountRef.AccountID)
	if subscriptionID == "" {
		return "", fmt.Errorf("azure subscription id is required for AKS managed identity")
	}

	return buildUserAssignedIdentityResourceID(
		subscriptionID,
		controllers.GetResourceGroupName(c.VPC),
		aksControlPlaneManagedIdentityName(c.APPBox),
	), nil
}

func buildUserAssignedIdentityResourceID(subscriptionID, resourceGroupName, identityName string) string {
	return fmt.Sprintf(userAssignedIdentityResourceIDFormat, subscriptionID, resourceGroupName, identityName)
}
