package dbuser

import (
	"context"

	"go.uber.org/zap"

	"github.com/tidbcloud/tiinf/monitor/tilog"

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

func (d *DBUserDao) CreateCommandOrgKey(ctx context.Context, tx *gorm.DB, orgId uint64, status entity.CommandStatus, action entity.CommandAction) error {
	entity := &entity.CommandOrgKey{OrgID: entity.ID(orgId), Status: status, Action: action}
	err := tx.Create(entity).Error
	if err != nil {
		return err
	}
	tilog.Info(ctx, "CreateCommandOrgKey success", zap.Any("entity", entity))
	return nil
}
func (d *DBUserDao) ListCommandOrgKeys(ctx context.Context, tx *gorm.DB, filter CommandOrgKeyFilter) ([]entity.CommandOrgKey, error) {
	var orgKeys []entity.CommandOrgKey

	qs := entity.NewCommandOrgKeyQuerySet(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(&orgKeys)
	if err != nil {
		return nil, err
	}

	return orgKeys, nil
}

func (d *DBUserDao) UpdateCommandOrgKey(ctx context.Context, tx *gorm.DB, orgId uint64, status entity.CommandStatus, action entity.CommandAction) error {
	updater := entity.NewCommandOrgKeyQuerySet(tx).OrgIDEq(entity.ID(orgId)).GetUpdater()

	if status != "" {
		updater.SetStatus(status)
	}
	if action != "" {
		updater.SetAction(action)
	}

	err := updater.Update()

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

func (d *DBUserDao) DeleteCommandOrgKey(ctx context.Context, tx *gorm.DB, orgId uint64) error {
	err := entity.NewCommandOrgKeyQuerySet(tx).OrgIDEq(entity.ID(orgId)).Delete()

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