package dbuser

import (
	"context"

	"github.com/tidbcloud/tiinf/monitor/tilog"
	"go.uber.org/zap"

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

func (d *DBUserDao) CreateCommandUserAction(ctx context.Context, tx *gorm.DB, operator uint64, userId uint64, email string, orgId uint64, projectId uint64, status entity.CommandStatus, action entity.CommandAction, targetType entity.TargetType, operatorType entity.TargetType) error {

	obj := &entity.CommandUserAction{OrgID: entity.ID(orgId), Operator: entity.ID(operator), UserID: entity.ID(userId), Email: email, ProjectID: entity.ID(projectId), Status: status, Action: action, TargetType: targetType, OperatorType: operatorType}
	err := tx.Create(obj).Error
	if err != nil {
		return err
	}
	tilog.Info(ctx, "CreateCommandUserAction  success ", zap.Any("CommandUserAction", obj))
	return nil
}
func (d *DBUserDao) ListCommandUserActions(ctx context.Context, tx *gorm.DB, filter CommandUserActionFilter) ([]entity.CommandUserAction, error) {
	var objs []entity.CommandUserAction

	qs := entity.NewCommandUserActionQuerySet(tx)

	if len(filter.UserIDs) > 0 {
		qs = qs.UserIDIn(filter.UserIDs...)
	}

	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...)
	}
	if filter.CreatedAtGte != nil {
		qs = qs.CreatedAtGte(*filter.CreatedAtGte)
	}
	qs = qs.OrderAscByID()

	err := qs.All(&objs)
	if err != nil {
		return nil, err
	}

	return objs, nil
}

func (d *DBUserDao) UpdateCommandUserAction(ctx context.Context, tx *gorm.DB, id uint64, operator uint64, userId uint64, orgId uint64, projectId uint64, status entity.CommandStatus, action entity.CommandAction) error {

	updater := entity.NewCommandUserActionQuerySet(tx).IDEq(entity.ID(id)).GetUpdater()

	if status != "" {
		updater.SetStatus(status)
	}
	if action != "" {
		updater.SetAction(action)
	}
	if orgId != 0 {
		updater.SetOrgID(entity.ID(orgId))
	}
	if projectId != 0 {
		updater.SetProjectID(entity.ID(projectId))
	}

	updater.SetOperator(entity.ID(operator))
	updater.SetUserID(entity.ID(userId))

	err := updater.Update()

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

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

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