package audit

import (
	"context"

	apps "k8s.io/api/apps/v1"
	"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
	"k8s.io/apimachinery/pkg/runtime/schema"
	"k8s.io/apimachinery/pkg/util/json"
	"sigs.k8s.io/controller-runtime/pkg/client"
)

// getAdvanceStatefulset get from AdvanceStatefulset.
// Note the spec is same, to avoid many issues dependents on k8s repo we DO NOT use the client pkg:
// https://github.com/pingcap/advanced-statefulset/tree/master/client
func getAdvanceStatefulset(ctx context.Context, cli client.Client, key client.ObjectKey, sts *apps.StatefulSet) error {
	u := &unstructured.Unstructured{}
	u.SetGroupVersionKind(schema.GroupVersionKind{
		Group:   "apps.pingcap.com",
		Version: "v1",
		Kind:    "StatefulSet",
	})

	err := cli.Get(ctx, key, u)
	if err != nil {
		return err
	}

	data, err := u.MarshalJSON()
	if err != nil {
		return err
	}

	err = json.Unmarshal(data, sts)
	if err != nil {
		return err
	}

	return nil
}

func deleteAdvanceStatefuleset(
	ctx context.Context,
	cli client.Client,
	key client.ObjectKey,
	opts ...client.DeleteOption,
) error {
	u := &unstructured.Unstructured{}
	u.SetGroupVersionKind(schema.GroupVersionKind{
		Group:   "apps.pingcap.com",
		Version: "v1",
		Kind:    "StatefulSet",
	})

	u.SetNamespace(key.Namespace)
	u.SetName(key.Name)

	err := cli.Delete(ctx, u, opts...)
	if err != nil {
		return err
	}

	return nil
}
