package dbuser

import (
	"context"

	"github.com/tidbcloud/tiinf/errs"

	"github.com/tidbcloud/account/internel/dao/entity"
	"gorm.io/gorm"
)

// cluster_key

func (d *DBUserDao) CreateCommandClusterKey(ctx context.Context, tx *gorm.DB, orgId uint64, clusterId uint64, status entity.CommandStatus, action entity.CommandAction) error {
	obj := &entity.CommandClusterKey{OrgID: entity.ID(orgId), ClusterID: entity.ID(clusterId), Status: status, Action: action}
	err := tx.Create(obj).Error
	if err != nil {
		return err
	}

	return nil
}
func (d *DBUserDao) ListCommandClusterKeys(ctx context.Context, tx *gorm.DB, filter CommandClusterKeyFilter) ([]entity.CommandClusterKey, error) {
	var objs []entity.CommandClusterKey

	qs := entity.NewCommandClusterKeyQuerySet(tx)

	if len(filter.OrgIDs) > 0 {
		qs = qs.OrgIDIn(filter.OrgIDs...)
	}

	if len(filter.Status) > 0 {
		qs = qs.StatusIn(filter.Status...)
	}
	if len(filter.Actions) > 0 {
		qs = qs.ActionIn(filter.Actions...)
	}
	qs = qs.OrderAscByID()
	err := qs.All(&objs)
	if err != nil {
		return nil, err
	}

	return objs, nil
}

func (d *DBUserDao) UpdateCommandClusterKey(ctx context.Context, tx *gorm.DB, e entity.CommandClusterKey) error {
	if e.ID == 0 {
		return errs.NewBadRequest("id must be not null", nil)
	}
	updater := entity.NewCommandClusterKeyQuerySet(tx).IDEq(e.ID).GetUpdater()

	if e.Status != "" {
		updater.SetStatus(e.Status)
	}
	if e.Action != "" {
		updater.SetAction(e.Action)
	}
	if e.ClusterID != 0 {
		updater.SetClusterID(e.ClusterID)
	}
	if e.OrgID != 0 {
		updater.SetOrgID(e.OrgID)
	}

	err := updater.Update()

	if err != nil {
		return err
	}
	return nil
}

func (d *DBUserDao) DeleteCommandClusterKey(ctx context.Context, tx *gorm.DB, id uint64) error {
	err := entity.NewOrgKeyQuerySet(tx).IDEq(entity.ID(id)).Delete()

	if err != nil {
		return err
	}
	return nil
}
