package tidbcluster_config_schema

import (
	"context"
	"encoding/json"

	"github.com/pingcap/log"
	"github.com/pingcap/tep/pkg/apis/apiserver"
	"github.com/pingcap/tep/pkg/operator"
	store "github.com/pingcap/tep/pkg/registry/apiserver"
	schemaObj "github.com/pingcap/tep/pkg/schema"
	"go.uber.org/zap"
	"k8s.io/apimachinery/pkg/api/errors"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/apimachinery/pkg/runtime"
	"k8s.io/apimachinery/pkg/runtime/schema"
)

type Storage struct {
	store         *store.Store
	groupResource schema.GroupResource
}

func NewStorage(store *store.Store, groupResource schema.GroupResource) *Storage {
	return &Storage{
		store:         store,
		groupResource: groupResource,
	}
}

func (s *Storage) Kind() string {
	return "TiDBClusterConfigSchema"
}

func (s *Storage) New() runtime.Object {
	return &apiserver.TiDBClusterConfigSchema{}
}

func (s *Storage) NamespaceScoped() bool {
	return false
}

func (s *Storage) Get(ctx context.Context, name string, options *metav1.GetOptions) (runtime.Object, error) {
	if name != operator.DefaultConfigSchemaName {
		return nil, errors.NewNotFound(s.groupResource, name)
	}
	tidbConfig := schemaObj.GetConfigSchema()
	b, err := json.Marshal(tidbConfig)
	if err != nil {
		log.Error("failed to decode tidbcluster config schema", zap.Error(err))
		return nil, errors.NewInternalError(err)
	}
	return &apiserver.TiDBClusterConfigSchema{
		ObjectMeta: metav1.ObjectMeta{
			Name: name,
		},
		Schema: b,
	}, nil
}
