package alert

import (
	"context"
	"github.com/pingcap/tep/pkg/apis/apiserver"
	store "github.com/pingcap/tep/pkg/registry/apiserver"
	"github.com/pingcap/tep/pkg/utils/alert"
	"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"
	"k8s.io/apiserver/pkg/registry/rest"
)

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

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

func (s *AlertWebhookStorage) Kind() string {
	return "AlertWebhook"
}

func (s *AlertWebhookStorage) Create(ctx context.Context, obj runtime.Object, createValidation rest.ValidateObjectFunc, options *metav1.CreateOptions) (runtime.Object, error) {
	group := obj.(*apiserver.AlertGroup)

	err := alert.Save(group, s.store.DB)
	if err != nil {
		return nil, errors.NewBadRequest(err.Error())
	}

	return &apiserver.AlertGroup{}, nil
}

func (s *AlertWebhookStorage) New() runtime.Object {
	return &apiserver.AlertGroup{}
}

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