package dbutil

import (
	"context"

	"github.com/pingcap/dbaas/central/db/entity"
	"gorm.io/gorm"
)

func UpdateClusterConfig(ctx context.Context, tx *gorm.DB, clusterID entity.ID, isAuditLogOn bool, auditLogConfig string) error {
	var item entity.ClusterConfig
	err := entity.NewClusterConfigQuerySet(tx).ClusterIDEq(clusterID).One(&item)
	if err != nil {
		return err
	}

	return entity.NewClusterConfigQuerySet(tx).ClusterIDEq(clusterID).GetUpdater().SetAuditLogConfig(auditLogConfig).SetIsAuditLogOn(isAuditLogOn).Update()
}

func CreateClusterConfig(ctx context.Context, tx *gorm.DB, clusterID entity.ID, auditLogConfig string, isAuditLogOn bool) error {
	item := entity.ClusterConfig{
		ClusterID:      clusterID,
		AuditLogConfig: auditLogConfig,
		IsAuditLogOn:   isAuditLogOn,
	}
	return tx.Create(&item).Error
}

func UpdateClusterAuditLogStatus(ctx context.Context, tx *gorm.DB, clusterID entity.ID, isAuditLogOn bool) error {
	return entity.NewClusterConfigQuerySet(tx).ClusterIDEq(clusterID).GetUpdater().SetIsAuditLogOn(isAuditLogOn).Update()
}

func GetClusterConfig(ctx context.Context, tx *gorm.DB, clusterID entity.ID) (*entity.ClusterConfig, error) {
	var item entity.ClusterConfig
	err := entity.NewClusterConfigQuerySet(tx).ClusterIDEq(clusterID).One(&item)

	return &item, err
}

func UpsertClusterConfig(ctx context.Context, tx *gorm.DB, clusterID entity.ID, isAuditLogOn bool, auditLogConfig string) error {
	_, err := GetClusterConfig(ctx, tx, clusterID)
	if err == gorm.ErrRecordNotFound {
		return CreateClusterConfig(ctx, tx, clusterID, auditLogConfig, isAuditLogOn)
	}

	if err != nil {
		return err
	}

	return UpdateClusterConfig(ctx, tx, clusterID, isAuditLogOn, auditLogConfig)
}
