package task

import (
	"context"
	"encoding/json"
	"fmt"

	"github.com/tidbcloud/infra-provider/regional-server/api/v1alpha1"
	"github.com/tidbcloud/infra-provider/regional-server/pkg/controllers"
	"github.com/tidbcloud/infra-provider/regional-server/pkg/namer"
	apierrors "k8s.io/apimachinery/pkg/api/errors"
	"k8s.io/utils/ptr"
	"sigs.k8s.io/controller-runtime/pkg/client"
)

// GenerateKeyName returns the unique Crossplane resource name for a Key CR.
func GenerateKeyName(key *v1alpha1.Key, prefix string) string {
	return controllers.UniqueIdentifier(key.ObjectMeta, namer.WithPrefix(prefix))
}

// ContainsPrincipal checks if a target principal ARN is present in a JSON key policy
// under the given principalKey (e.g. "AWS" for AWS IAM, "RAM" for Aliyun RAM).
func ContainsPrincipal(target string, policyPtr *string, principalKey string) bool {
	policyStr := ptr.Deref(policyPtr, "")
	if policyStr == "" {
		return false
	}

	var doc map[string]interface{}
	if err := json.Unmarshal([]byte(policyStr), &doc); err != nil {
		return false
	}

	statements, ok := doc["Statement"].([]interface{})
	if !ok {
		return false
	}

	for _, stmt := range statements {
		stmtMap, ok := stmt.(map[string]interface{})
		if !ok {
			continue
		}

		principal, ok := stmtMap["Principal"].(map[string]interface{})
		if !ok {
			continue
		}

		val, ok := principal[principalKey]
		if !ok {
			continue
		}

		switch v := val.(type) {
		case string:
			if v == target {
				return true
			}
		case []interface{}:
			for _, item := range v {
				s, ok := item.(string)
				if !ok {
					continue
				}
				if s == target {
					return true
				}
			}
		}
	}

	return false
}

// LookupNodeRoleARN resolves a trusted dataplane ID to its node role ARN.
// Returns the ARN, or ("", nil) if not ready yet, or an error.
func LookupNodeRoleARN(ctx context.Context, cli client.Client, key *v1alpha1.Key, trustedDataplaneId string) (string, error) {
	dataPlaneCR := &v1alpha1.DataPlane{}
	if err := cli.Get(ctx, client.ObjectKey{
		Namespace: key.Namespace,
		Name:      trustedDataplaneId,
	}, dataPlaneCR); err != nil {
		if apierrors.IsNotFound(err) {
			return "", nil
		}
		return "", fmt.Errorf("failed to get dataplane %s: %w", trustedDataplaneId, err)
	}
	if dataPlaneCR.Status.AppBox == nil || dataPlaneCR.Status.AppBox.Name == "" {
		return "", nil
	}
	appBoxCR := &v1alpha1.APPBox{}
	if err := cli.Get(ctx, client.ObjectKey{
		Namespace: key.Namespace,
		Name:      dataPlaneCR.Status.AppBox.Name,
	}, appBoxCR); err != nil {
		if apierrors.IsNotFound(err) {
			return "", nil
		}
		return "", fmt.Errorf("failed to get appbox %s: %w", dataPlaneCR.Status.AppBox.Name, err)
	}
	return appBoxCR.Status.IAM.NodeRoleARN, nil
}
