package monitoring

import (
	"context"

	"gitlink.org.cn/JointCloud/pcm-coordinator/internal/svc"
	"gitlink.org.cn/JointCloud/pcm-coordinator/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type DeleteAlertRuleLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewDeleteAlertRuleLogic(ctx context.Context, svcCtx *svc.ServiceContext) *DeleteAlertRuleLogic {
	return &DeleteAlertRuleLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *DeleteAlertRuleLogic) DeleteAlertRule(req *types.DeleteAlertRuleReq) error {
	// Delete data from the database
	l.svcCtx.DbEngin.Delete(&types.AlertRule{}, "id = ?", req.Id)

	// query cluster http url.
	var server string
	l.svcCtx.DbEngin.Raw("select ta.server from t_adapter ta,t_cluster tc where ta.id = tc.adapter_id and tc.name = ?", &req.ClusterName).Scan(&server)

	// create prometheus rule
	response, err := l.svcCtx.HttpClient.R().
		SetBody(&CrdStruct{
			ClusterName: req.ClusterName,
			Name:        req.Name,
			Grv: Grv{
				Group:    "monitoring.coreos.com",
				Version:  "v1",
				Resource: "prometheusrules",
			},
		}).
		ForceContentType("application/json").
		Delete(server + "/api/v1/crd")
	if err != nil {
		return err
	}
	if err != nil || response.IsError() {
		return err
	}
	return nil
}

type Grv struct {
	Group    string `json:"group"`
	Version  string `json:"version"`
	Resource string `json:"resource"`
}

type CrdStruct struct {
	ClusterName string `json:"clusterName"`
	Grv         Grv    `json:"grv"`
	Name        string `json:"name"`
}
