package publish

import (
	"context"

	"github.com/tidbcloud/account/commons/config"
	"github.com/tidbcloud/account/commons/eventbus"
	"github.com/tidbcloud/account/internel/dao/entity"
	"github.com/tidbcloud/tiinf/errs"
	"github.com/tidbcloud/tiinf/monitor/tilog"
	"go.uber.org/zap"
)

func PublishClusterDbUserEvent(ctx context.Context, data *ClusterDbUserEventData) error {
	if data == nil {
		tilog.Info(ctx, "PublishClusterDbUserEvent data is nil"+config.GetEnv())
		return errs.NewBadRequest("data is nil", nil)
	}
	if config.IsLocalEnv() {
		tilog.Info(ctx, "PublishClusterDbUserEvent skip "+config.GetEnv())
		return nil
	}
	if data.Action == string(entity.CommandActionCheck) {
		data.Action = string(entity.CommandActionCreate)
	}
	event := &eventbus.Event{
		EventID:   config.Group,
		EventType: config.EventTypeOperateClusterDbUser,
		EventData: data,
	}
	err := eventbus.Get().PublishEvent(config.EventTypeOperateClusterDbUser, event)
	if err != nil {
		tilog.Error(ctx, "PublishClusterDbUserEvent error", zap.Any("event", event), zap.Any("err", err))
		return err
	}
	tilog.Info(ctx, "PublishClusterDbUserEvent success", zap.Any("event", event))
	return nil

}

type ClusterDbUserEventData struct {
	ClusterID uint64 `json:"cluster_id"`
	DbUser    string `json:"db_user"`
	DbRole    string `json:"db_role"`
	Action    string `json:"action"` // action: create/delete
}
