// Code generated by ent, DO NOT EDIT.

package ent

import (
	"context"
	"errors"
	"fmt"
	"time"
	"wechat-api/ent/agent"
	"wechat-api/ent/predicate"
	"wechat-api/ent/token"
	"wechat-api/ent/wx"

	"entgo.io/ent/dialect/sql"
	"entgo.io/ent/dialect/sql/sqlgraph"
	"entgo.io/ent/schema/field"
)

// AgentUpdate is the builder for updating Agent entities.
type AgentUpdate struct {
	config
	hooks    []Hook
	mutation *AgentMutation
}

// Where appends a list predicates to the AgentUpdate builder.
func (au *AgentUpdate) Where(ps ...predicate.Agent) *AgentUpdate {
	au.mutation.Where(ps...)
	return au
}

// SetUpdatedAt sets the "updated_at" field.
func (au *AgentUpdate) SetUpdatedAt(t time.Time) *AgentUpdate {
	au.mutation.SetUpdatedAt(t)
	return au
}

// SetDeletedAt sets the "deleted_at" field.
func (au *AgentUpdate) SetDeletedAt(t time.Time) *AgentUpdate {
	au.mutation.SetDeletedAt(t)
	return au
}

// SetNillableDeletedAt sets the "deleted_at" field if the given value is not nil.
func (au *AgentUpdate) SetNillableDeletedAt(t *time.Time) *AgentUpdate {
	if t != nil {
		au.SetDeletedAt(*t)
	}
	return au
}

// ClearDeletedAt clears the value of the "deleted_at" field.
func (au *AgentUpdate) ClearDeletedAt() *AgentUpdate {
	au.mutation.ClearDeletedAt()
	return au
}

// SetName sets the "name" field.
func (au *AgentUpdate) SetName(s string) *AgentUpdate {
	au.mutation.SetName(s)
	return au
}

// SetNillableName sets the "name" field if the given value is not nil.
func (au *AgentUpdate) SetNillableName(s *string) *AgentUpdate {
	if s != nil {
		au.SetName(*s)
	}
	return au
}

// SetRole sets the "role" field.
func (au *AgentUpdate) SetRole(s string) *AgentUpdate {
	au.mutation.SetRole(s)
	return au
}

// SetNillableRole sets the "role" field if the given value is not nil.
func (au *AgentUpdate) SetNillableRole(s *string) *AgentUpdate {
	if s != nil {
		au.SetRole(*s)
	}
	return au
}

// SetStatus sets the "status" field.
func (au *AgentUpdate) SetStatus(i int) *AgentUpdate {
	au.mutation.ResetStatus()
	au.mutation.SetStatus(i)
	return au
}

// SetNillableStatus sets the "status" field if the given value is not nil.
func (au *AgentUpdate) SetNillableStatus(i *int) *AgentUpdate {
	if i != nil {
		au.SetStatus(*i)
	}
	return au
}

// AddStatus adds i to the "status" field.
func (au *AgentUpdate) AddStatus(i int) *AgentUpdate {
	au.mutation.AddStatus(i)
	return au
}

// ClearStatus clears the value of the "status" field.
func (au *AgentUpdate) ClearStatus() *AgentUpdate {
	au.mutation.ClearStatus()
	return au
}

// SetBackground sets the "background" field.
func (au *AgentUpdate) SetBackground(s string) *AgentUpdate {
	au.mutation.SetBackground(s)
	return au
}

// SetNillableBackground sets the "background" field if the given value is not nil.
func (au *AgentUpdate) SetNillableBackground(s *string) *AgentUpdate {
	if s != nil {
		au.SetBackground(*s)
	}
	return au
}

// ClearBackground clears the value of the "background" field.
func (au *AgentUpdate) ClearBackground() *AgentUpdate {
	au.mutation.ClearBackground()
	return au
}

// SetExamples sets the "examples" field.
func (au *AgentUpdate) SetExamples(s string) *AgentUpdate {
	au.mutation.SetExamples(s)
	return au
}

// SetNillableExamples sets the "examples" field if the given value is not nil.
func (au *AgentUpdate) SetNillableExamples(s *string) *AgentUpdate {
	if s != nil {
		au.SetExamples(*s)
	}
	return au
}

// ClearExamples clears the value of the "examples" field.
func (au *AgentUpdate) ClearExamples() *AgentUpdate {
	au.mutation.ClearExamples()
	return au
}

// SetOrganizationID sets the "organization_id" field.
func (au *AgentUpdate) SetOrganizationID(u uint64) *AgentUpdate {
	au.mutation.ResetOrganizationID()
	au.mutation.SetOrganizationID(u)
	return au
}

// SetNillableOrganizationID sets the "organization_id" field if the given value is not nil.
func (au *AgentUpdate) SetNillableOrganizationID(u *uint64) *AgentUpdate {
	if u != nil {
		au.SetOrganizationID(*u)
	}
	return au
}

// AddOrganizationID adds u to the "organization_id" field.
func (au *AgentUpdate) AddOrganizationID(u int64) *AgentUpdate {
	au.mutation.AddOrganizationID(u)
	return au
}

// SetDatasetID sets the "dataset_id" field.
func (au *AgentUpdate) SetDatasetID(s string) *AgentUpdate {
	au.mutation.SetDatasetID(s)
	return au
}

// SetNillableDatasetID sets the "dataset_id" field if the given value is not nil.
func (au *AgentUpdate) SetNillableDatasetID(s *string) *AgentUpdate {
	if s != nil {
		au.SetDatasetID(*s)
	}
	return au
}

// SetCollectionID sets the "collection_id" field.
func (au *AgentUpdate) SetCollectionID(s string) *AgentUpdate {
	au.mutation.SetCollectionID(s)
	return au
}

// SetNillableCollectionID sets the "collection_id" field if the given value is not nil.
func (au *AgentUpdate) SetNillableCollectionID(s *string) *AgentUpdate {
	if s != nil {
		au.SetCollectionID(*s)
	}
	return au
}

// AddWxAgentIDs adds the "wx_agent" edge to the Wx entity by IDs.
func (au *AgentUpdate) AddWxAgentIDs(ids ...uint64) *AgentUpdate {
	au.mutation.AddWxAgentIDs(ids...)
	return au
}

// AddWxAgent adds the "wx_agent" edges to the Wx entity.
func (au *AgentUpdate) AddWxAgent(w ...*Wx) *AgentUpdate {
	ids := make([]uint64, len(w))
	for i := range w {
		ids[i] = w[i].ID
	}
	return au.AddWxAgentIDs(ids...)
}

// AddTokenAgentIDs adds the "token_agent" edge to the Token entity by IDs.
func (au *AgentUpdate) AddTokenAgentIDs(ids ...uint64) *AgentUpdate {
	au.mutation.AddTokenAgentIDs(ids...)
	return au
}

// AddTokenAgent adds the "token_agent" edges to the Token entity.
func (au *AgentUpdate) AddTokenAgent(t ...*Token) *AgentUpdate {
	ids := make([]uint64, len(t))
	for i := range t {
		ids[i] = t[i].ID
	}
	return au.AddTokenAgentIDs(ids...)
}

// Mutation returns the AgentMutation object of the builder.
func (au *AgentUpdate) Mutation() *AgentMutation {
	return au.mutation
}

// ClearWxAgent clears all "wx_agent" edges to the Wx entity.
func (au *AgentUpdate) ClearWxAgent() *AgentUpdate {
	au.mutation.ClearWxAgent()
	return au
}

// RemoveWxAgentIDs removes the "wx_agent" edge to Wx entities by IDs.
func (au *AgentUpdate) RemoveWxAgentIDs(ids ...uint64) *AgentUpdate {
	au.mutation.RemoveWxAgentIDs(ids...)
	return au
}

// RemoveWxAgent removes "wx_agent" edges to Wx entities.
func (au *AgentUpdate) RemoveWxAgent(w ...*Wx) *AgentUpdate {
	ids := make([]uint64, len(w))
	for i := range w {
		ids[i] = w[i].ID
	}
	return au.RemoveWxAgentIDs(ids...)
}

// ClearTokenAgent clears all "token_agent" edges to the Token entity.
func (au *AgentUpdate) ClearTokenAgent() *AgentUpdate {
	au.mutation.ClearTokenAgent()
	return au
}

// RemoveTokenAgentIDs removes the "token_agent" edge to Token entities by IDs.
func (au *AgentUpdate) RemoveTokenAgentIDs(ids ...uint64) *AgentUpdate {
	au.mutation.RemoveTokenAgentIDs(ids...)
	return au
}

// RemoveTokenAgent removes "token_agent" edges to Token entities.
func (au *AgentUpdate) RemoveTokenAgent(t ...*Token) *AgentUpdate {
	ids := make([]uint64, len(t))
	for i := range t {
		ids[i] = t[i].ID
	}
	return au.RemoveTokenAgentIDs(ids...)
}

// Save executes the query and returns the number of nodes affected by the update operation.
func (au *AgentUpdate) Save(ctx context.Context) (int, error) {
	if err := au.defaults(); err != nil {
		return 0, err
	}
	return withHooks(ctx, au.sqlSave, au.mutation, au.hooks)
}

// SaveX is like Save, but panics if an error occurs.
func (au *AgentUpdate) SaveX(ctx context.Context) int {
	affected, err := au.Save(ctx)
	if err != nil {
		panic(err)
	}
	return affected
}

// Exec executes the query.
func (au *AgentUpdate) Exec(ctx context.Context) error {
	_, err := au.Save(ctx)
	return err
}

// ExecX is like Exec, but panics if an error occurs.
func (au *AgentUpdate) ExecX(ctx context.Context) {
	if err := au.Exec(ctx); err != nil {
		panic(err)
	}
}

// defaults sets the default values of the builder before save.
func (au *AgentUpdate) defaults() error {
	if _, ok := au.mutation.UpdatedAt(); !ok {
		if agent.UpdateDefaultUpdatedAt == nil {
			return fmt.Errorf("ent: uninitialized agent.UpdateDefaultUpdatedAt (forgotten import ent/runtime?)")
		}
		v := agent.UpdateDefaultUpdatedAt()
		au.mutation.SetUpdatedAt(v)
	}
	return nil
}

// check runs all checks and user-defined validators on the builder.
func (au *AgentUpdate) check() error {
	if v, ok := au.mutation.Name(); ok {
		if err := agent.NameValidator(v); err != nil {
			return &ValidationError{Name: "name", err: fmt.Errorf(`ent: validator failed for field "Agent.name": %w`, err)}
		}
	}
	if v, ok := au.mutation.Status(); ok {
		if err := agent.StatusValidator(v); err != nil {
			return &ValidationError{Name: "status", err: fmt.Errorf(`ent: validator failed for field "Agent.status": %w`, err)}
		}
	}
	if v, ok := au.mutation.OrganizationID(); ok {
		if err := agent.OrganizationIDValidator(v); err != nil {
			return &ValidationError{Name: "organization_id", err: fmt.Errorf(`ent: validator failed for field "Agent.organization_id": %w`, err)}
		}
	}
	if v, ok := au.mutation.DatasetID(); ok {
		if err := agent.DatasetIDValidator(v); err != nil {
			return &ValidationError{Name: "dataset_id", err: fmt.Errorf(`ent: validator failed for field "Agent.dataset_id": %w`, err)}
		}
	}
	if v, ok := au.mutation.CollectionID(); ok {
		if err := agent.CollectionIDValidator(v); err != nil {
			return &ValidationError{Name: "collection_id", err: fmt.Errorf(`ent: validator failed for field "Agent.collection_id": %w`, err)}
		}
	}
	return nil
}

func (au *AgentUpdate) sqlSave(ctx context.Context) (n int, err error) {
	if err := au.check(); err != nil {
		return n, err
	}
	_spec := sqlgraph.NewUpdateSpec(agent.Table, agent.Columns, sqlgraph.NewFieldSpec(agent.FieldID, field.TypeUint64))
	if ps := au.mutation.predicates; len(ps) > 0 {
		_spec.Predicate = func(selector *sql.Selector) {
			for i := range ps {
				ps[i](selector)
			}
		}
	}
	if value, ok := au.mutation.UpdatedAt(); ok {
		_spec.SetField(agent.FieldUpdatedAt, field.TypeTime, value)
	}
	if value, ok := au.mutation.DeletedAt(); ok {
		_spec.SetField(agent.FieldDeletedAt, field.TypeTime, value)
	}
	if au.mutation.DeletedAtCleared() {
		_spec.ClearField(agent.FieldDeletedAt, field.TypeTime)
	}
	if value, ok := au.mutation.Name(); ok {
		_spec.SetField(agent.FieldName, field.TypeString, value)
	}
	if value, ok := au.mutation.Role(); ok {
		_spec.SetField(agent.FieldRole, field.TypeString, value)
	}
	if value, ok := au.mutation.Status(); ok {
		_spec.SetField(agent.FieldStatus, field.TypeInt, value)
	}
	if value, ok := au.mutation.AddedStatus(); ok {
		_spec.AddField(agent.FieldStatus, field.TypeInt, value)
	}
	if au.mutation.StatusCleared() {
		_spec.ClearField(agent.FieldStatus, field.TypeInt)
	}
	if value, ok := au.mutation.Background(); ok {
		_spec.SetField(agent.FieldBackground, field.TypeString, value)
	}
	if au.mutation.BackgroundCleared() {
		_spec.ClearField(agent.FieldBackground, field.TypeString)
	}
	if value, ok := au.mutation.Examples(); ok {
		_spec.SetField(agent.FieldExamples, field.TypeString, value)
	}
	if au.mutation.ExamplesCleared() {
		_spec.ClearField(agent.FieldExamples, field.TypeString)
	}
	if value, ok := au.mutation.OrganizationID(); ok {
		_spec.SetField(agent.FieldOrganizationID, field.TypeUint64, value)
	}
	if value, ok := au.mutation.AddedOrganizationID(); ok {
		_spec.AddField(agent.FieldOrganizationID, field.TypeUint64, value)
	}
	if value, ok := au.mutation.DatasetID(); ok {
		_spec.SetField(agent.FieldDatasetID, field.TypeString, value)
	}
	if value, ok := au.mutation.CollectionID(); ok {
		_spec.SetField(agent.FieldCollectionID, field.TypeString, value)
	}
	if au.mutation.WxAgentCleared() {
		edge := &sqlgraph.EdgeSpec{
			Rel:     sqlgraph.O2M,
			Inverse: false,
			Table:   agent.WxAgentTable,
			Columns: []string{agent.WxAgentColumn},
			Bidi:    false,
			Target: &sqlgraph.EdgeTarget{
				IDSpec: sqlgraph.NewFieldSpec(wx.FieldID, field.TypeUint64),
			},
		}
		_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
	}
	if nodes := au.mutation.RemovedWxAgentIDs(); len(nodes) > 0 && !au.mutation.WxAgentCleared() {
		edge := &sqlgraph.EdgeSpec{
			Rel:     sqlgraph.O2M,
			Inverse: false,
			Table:   agent.WxAgentTable,
			Columns: []string{agent.WxAgentColumn},
			Bidi:    false,
			Target: &sqlgraph.EdgeTarget{
				IDSpec: sqlgraph.NewFieldSpec(wx.FieldID, field.TypeUint64),
			},
		}
		for _, k := range nodes {
			edge.Target.Nodes = append(edge.Target.Nodes, k)
		}
		_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
	}
	if nodes := au.mutation.WxAgentIDs(); len(nodes) > 0 {
		edge := &sqlgraph.EdgeSpec{
			Rel:     sqlgraph.O2M,
			Inverse: false,
			Table:   agent.WxAgentTable,
			Columns: []string{agent.WxAgentColumn},
			Bidi:    false,
			Target: &sqlgraph.EdgeTarget{
				IDSpec: sqlgraph.NewFieldSpec(wx.FieldID, field.TypeUint64),
			},
		}
		for _, k := range nodes {
			edge.Target.Nodes = append(edge.Target.Nodes, k)
		}
		_spec.Edges.Add = append(_spec.Edges.Add, edge)
	}
	if au.mutation.TokenAgentCleared() {
		edge := &sqlgraph.EdgeSpec{
			Rel:     sqlgraph.O2M,
			Inverse: false,
			Table:   agent.TokenAgentTable,
			Columns: []string{agent.TokenAgentColumn},
			Bidi:    false,
			Target: &sqlgraph.EdgeTarget{
				IDSpec: sqlgraph.NewFieldSpec(token.FieldID, field.TypeUint64),
			},
		}
		_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
	}
	if nodes := au.mutation.RemovedTokenAgentIDs(); len(nodes) > 0 && !au.mutation.TokenAgentCleared() {
		edge := &sqlgraph.EdgeSpec{
			Rel:     sqlgraph.O2M,
			Inverse: false,
			Table:   agent.TokenAgentTable,
			Columns: []string{agent.TokenAgentColumn},
			Bidi:    false,
			Target: &sqlgraph.EdgeTarget{
				IDSpec: sqlgraph.NewFieldSpec(token.FieldID, field.TypeUint64),
			},
		}
		for _, k := range nodes {
			edge.Target.Nodes = append(edge.Target.Nodes, k)
		}
		_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
	}
	if nodes := au.mutation.TokenAgentIDs(); len(nodes) > 0 {
		edge := &sqlgraph.EdgeSpec{
			Rel:     sqlgraph.O2M,
			Inverse: false,
			Table:   agent.TokenAgentTable,
			Columns: []string{agent.TokenAgentColumn},
			Bidi:    false,
			Target: &sqlgraph.EdgeTarget{
				IDSpec: sqlgraph.NewFieldSpec(token.FieldID, field.TypeUint64),
			},
		}
		for _, k := range nodes {
			edge.Target.Nodes = append(edge.Target.Nodes, k)
		}
		_spec.Edges.Add = append(_spec.Edges.Add, edge)
	}
	if n, err = sqlgraph.UpdateNodes(ctx, au.driver, _spec); err != nil {
		if _, ok := err.(*sqlgraph.NotFoundError); ok {
			err = &NotFoundError{agent.Label}
		} else if sqlgraph.IsConstraintError(err) {
			err = &ConstraintError{msg: err.Error(), wrap: err}
		}
		return 0, err
	}
	au.mutation.done = true
	return n, nil
}

// AgentUpdateOne is the builder for updating a single Agent entity.
type AgentUpdateOne struct {
	config
	fields   []string
	hooks    []Hook
	mutation *AgentMutation
}

// SetUpdatedAt sets the "updated_at" field.
func (auo *AgentUpdateOne) SetUpdatedAt(t time.Time) *AgentUpdateOne {
	auo.mutation.SetUpdatedAt(t)
	return auo
}

// SetDeletedAt sets the "deleted_at" field.
func (auo *AgentUpdateOne) SetDeletedAt(t time.Time) *AgentUpdateOne {
	auo.mutation.SetDeletedAt(t)
	return auo
}

// SetNillableDeletedAt sets the "deleted_at" field if the given value is not nil.
func (auo *AgentUpdateOne) SetNillableDeletedAt(t *time.Time) *AgentUpdateOne {
	if t != nil {
		auo.SetDeletedAt(*t)
	}
	return auo
}

// ClearDeletedAt clears the value of the "deleted_at" field.
func (auo *AgentUpdateOne) ClearDeletedAt() *AgentUpdateOne {
	auo.mutation.ClearDeletedAt()
	return auo
}

// SetName sets the "name" field.
func (auo *AgentUpdateOne) SetName(s string) *AgentUpdateOne {
	auo.mutation.SetName(s)
	return auo
}

// SetNillableName sets the "name" field if the given value is not nil.
func (auo *AgentUpdateOne) SetNillableName(s *string) *AgentUpdateOne {
	if s != nil {
		auo.SetName(*s)
	}
	return auo
}

// SetRole sets the "role" field.
func (auo *AgentUpdateOne) SetRole(s string) *AgentUpdateOne {
	auo.mutation.SetRole(s)
	return auo
}

// SetNillableRole sets the "role" field if the given value is not nil.
func (auo *AgentUpdateOne) SetNillableRole(s *string) *AgentUpdateOne {
	if s != nil {
		auo.SetRole(*s)
	}
	return auo
}

// SetStatus sets the "status" field.
func (auo *AgentUpdateOne) SetStatus(i int) *AgentUpdateOne {
	auo.mutation.ResetStatus()
	auo.mutation.SetStatus(i)
	return auo
}

// SetNillableStatus sets the "status" field if the given value is not nil.
func (auo *AgentUpdateOne) SetNillableStatus(i *int) *AgentUpdateOne {
	if i != nil {
		auo.SetStatus(*i)
	}
	return auo
}

// AddStatus adds i to the "status" field.
func (auo *AgentUpdateOne) AddStatus(i int) *AgentUpdateOne {
	auo.mutation.AddStatus(i)
	return auo
}

// ClearStatus clears the value of the "status" field.
func (auo *AgentUpdateOne) ClearStatus() *AgentUpdateOne {
	auo.mutation.ClearStatus()
	return auo
}

// SetBackground sets the "background" field.
func (auo *AgentUpdateOne) SetBackground(s string) *AgentUpdateOne {
	auo.mutation.SetBackground(s)
	return auo
}

// SetNillableBackground sets the "background" field if the given value is not nil.
func (auo *AgentUpdateOne) SetNillableBackground(s *string) *AgentUpdateOne {
	if s != nil {
		auo.SetBackground(*s)
	}
	return auo
}

// ClearBackground clears the value of the "background" field.
func (auo *AgentUpdateOne) ClearBackground() *AgentUpdateOne {
	auo.mutation.ClearBackground()
	return auo
}

// SetExamples sets the "examples" field.
func (auo *AgentUpdateOne) SetExamples(s string) *AgentUpdateOne {
	auo.mutation.SetExamples(s)
	return auo
}

// SetNillableExamples sets the "examples" field if the given value is not nil.
func (auo *AgentUpdateOne) SetNillableExamples(s *string) *AgentUpdateOne {
	if s != nil {
		auo.SetExamples(*s)
	}
	return auo
}

// ClearExamples clears the value of the "examples" field.
func (auo *AgentUpdateOne) ClearExamples() *AgentUpdateOne {
	auo.mutation.ClearExamples()
	return auo
}

// SetOrganizationID sets the "organization_id" field.
func (auo *AgentUpdateOne) SetOrganizationID(u uint64) *AgentUpdateOne {
	auo.mutation.ResetOrganizationID()
	auo.mutation.SetOrganizationID(u)
	return auo
}

// SetNillableOrganizationID sets the "organization_id" field if the given value is not nil.
func (auo *AgentUpdateOne) SetNillableOrganizationID(u *uint64) *AgentUpdateOne {
	if u != nil {
		auo.SetOrganizationID(*u)
	}
	return auo
}

// AddOrganizationID adds u to the "organization_id" field.
func (auo *AgentUpdateOne) AddOrganizationID(u int64) *AgentUpdateOne {
	auo.mutation.AddOrganizationID(u)
	return auo
}

// SetDatasetID sets the "dataset_id" field.
func (auo *AgentUpdateOne) SetDatasetID(s string) *AgentUpdateOne {
	auo.mutation.SetDatasetID(s)
	return auo
}

// SetNillableDatasetID sets the "dataset_id" field if the given value is not nil.
func (auo *AgentUpdateOne) SetNillableDatasetID(s *string) *AgentUpdateOne {
	if s != nil {
		auo.SetDatasetID(*s)
	}
	return auo
}

// SetCollectionID sets the "collection_id" field.
func (auo *AgentUpdateOne) SetCollectionID(s string) *AgentUpdateOne {
	auo.mutation.SetCollectionID(s)
	return auo
}

// SetNillableCollectionID sets the "collection_id" field if the given value is not nil.
func (auo *AgentUpdateOne) SetNillableCollectionID(s *string) *AgentUpdateOne {
	if s != nil {
		auo.SetCollectionID(*s)
	}
	return auo
}

// AddWxAgentIDs adds the "wx_agent" edge to the Wx entity by IDs.
func (auo *AgentUpdateOne) AddWxAgentIDs(ids ...uint64) *AgentUpdateOne {
	auo.mutation.AddWxAgentIDs(ids...)
	return auo
}

// AddWxAgent adds the "wx_agent" edges to the Wx entity.
func (auo *AgentUpdateOne) AddWxAgent(w ...*Wx) *AgentUpdateOne {
	ids := make([]uint64, len(w))
	for i := range w {
		ids[i] = w[i].ID
	}
	return auo.AddWxAgentIDs(ids...)
}

// AddTokenAgentIDs adds the "token_agent" edge to the Token entity by IDs.
func (auo *AgentUpdateOne) AddTokenAgentIDs(ids ...uint64) *AgentUpdateOne {
	auo.mutation.AddTokenAgentIDs(ids...)
	return auo
}

// AddTokenAgent adds the "token_agent" edges to the Token entity.
func (auo *AgentUpdateOne) AddTokenAgent(t ...*Token) *AgentUpdateOne {
	ids := make([]uint64, len(t))
	for i := range t {
		ids[i] = t[i].ID
	}
	return auo.AddTokenAgentIDs(ids...)
}

// Mutation returns the AgentMutation object of the builder.
func (auo *AgentUpdateOne) Mutation() *AgentMutation {
	return auo.mutation
}

// ClearWxAgent clears all "wx_agent" edges to the Wx entity.
func (auo *AgentUpdateOne) ClearWxAgent() *AgentUpdateOne {
	auo.mutation.ClearWxAgent()
	return auo
}

// RemoveWxAgentIDs removes the "wx_agent" edge to Wx entities by IDs.
func (auo *AgentUpdateOne) RemoveWxAgentIDs(ids ...uint64) *AgentUpdateOne {
	auo.mutation.RemoveWxAgentIDs(ids...)
	return auo
}

// RemoveWxAgent removes "wx_agent" edges to Wx entities.
func (auo *AgentUpdateOne) RemoveWxAgent(w ...*Wx) *AgentUpdateOne {
	ids := make([]uint64, len(w))
	for i := range w {
		ids[i] = w[i].ID
	}
	return auo.RemoveWxAgentIDs(ids...)
}

// ClearTokenAgent clears all "token_agent" edges to the Token entity.
func (auo *AgentUpdateOne) ClearTokenAgent() *AgentUpdateOne {
	auo.mutation.ClearTokenAgent()
	return auo
}

// RemoveTokenAgentIDs removes the "token_agent" edge to Token entities by IDs.
func (auo *AgentUpdateOne) RemoveTokenAgentIDs(ids ...uint64) *AgentUpdateOne {
	auo.mutation.RemoveTokenAgentIDs(ids...)
	return auo
}

// RemoveTokenAgent removes "token_agent" edges to Token entities.
func (auo *AgentUpdateOne) RemoveTokenAgent(t ...*Token) *AgentUpdateOne {
	ids := make([]uint64, len(t))
	for i := range t {
		ids[i] = t[i].ID
	}
	return auo.RemoveTokenAgentIDs(ids...)
}

// Where appends a list predicates to the AgentUpdate builder.
func (auo *AgentUpdateOne) Where(ps ...predicate.Agent) *AgentUpdateOne {
	auo.mutation.Where(ps...)
	return auo
}

// Select allows selecting one or more fields (columns) of the returned entity.
// The default is selecting all fields defined in the entity schema.
func (auo *AgentUpdateOne) Select(field string, fields ...string) *AgentUpdateOne {
	auo.fields = append([]string{field}, fields...)
	return auo
}

// Save executes the query and returns the updated Agent entity.
func (auo *AgentUpdateOne) Save(ctx context.Context) (*Agent, error) {
	if err := auo.defaults(); err != nil {
		return nil, err
	}
	return withHooks(ctx, auo.sqlSave, auo.mutation, auo.hooks)
}

// SaveX is like Save, but panics if an error occurs.
func (auo *AgentUpdateOne) SaveX(ctx context.Context) *Agent {
	node, err := auo.Save(ctx)
	if err != nil {
		panic(err)
	}
	return node
}

// Exec executes the query on the entity.
func (auo *AgentUpdateOne) Exec(ctx context.Context) error {
	_, err := auo.Save(ctx)
	return err
}

// ExecX is like Exec, but panics if an error occurs.
func (auo *AgentUpdateOne) ExecX(ctx context.Context) {
	if err := auo.Exec(ctx); err != nil {
		panic(err)
	}
}

// defaults sets the default values of the builder before save.
func (auo *AgentUpdateOne) defaults() error {
	if _, ok := auo.mutation.UpdatedAt(); !ok {
		if agent.UpdateDefaultUpdatedAt == nil {
			return fmt.Errorf("ent: uninitialized agent.UpdateDefaultUpdatedAt (forgotten import ent/runtime?)")
		}
		v := agent.UpdateDefaultUpdatedAt()
		auo.mutation.SetUpdatedAt(v)
	}
	return nil
}

// check runs all checks and user-defined validators on the builder.
func (auo *AgentUpdateOne) check() error {
	if v, ok := auo.mutation.Name(); ok {
		if err := agent.NameValidator(v); err != nil {
			return &ValidationError{Name: "name", err: fmt.Errorf(`ent: validator failed for field "Agent.name": %w`, err)}
		}
	}
	if v, ok := auo.mutation.Status(); ok {
		if err := agent.StatusValidator(v); err != nil {
			return &ValidationError{Name: "status", err: fmt.Errorf(`ent: validator failed for field "Agent.status": %w`, err)}
		}
	}
	if v, ok := auo.mutation.OrganizationID(); ok {
		if err := agent.OrganizationIDValidator(v); err != nil {
			return &ValidationError{Name: "organization_id", err: fmt.Errorf(`ent: validator failed for field "Agent.organization_id": %w`, err)}
		}
	}
	if v, ok := auo.mutation.DatasetID(); ok {
		if err := agent.DatasetIDValidator(v); err != nil {
			return &ValidationError{Name: "dataset_id", err: fmt.Errorf(`ent: validator failed for field "Agent.dataset_id": %w`, err)}
		}
	}
	if v, ok := auo.mutation.CollectionID(); ok {
		if err := agent.CollectionIDValidator(v); err != nil {
			return &ValidationError{Name: "collection_id", err: fmt.Errorf(`ent: validator failed for field "Agent.collection_id": %w`, err)}
		}
	}
	return nil
}

func (auo *AgentUpdateOne) sqlSave(ctx context.Context) (_node *Agent, err error) {
	if err := auo.check(); err != nil {
		return _node, err
	}
	_spec := sqlgraph.NewUpdateSpec(agent.Table, agent.Columns, sqlgraph.NewFieldSpec(agent.FieldID, field.TypeUint64))
	id, ok := auo.mutation.ID()
	if !ok {
		return nil, &ValidationError{Name: "id", err: errors.New(`ent: missing "Agent.id" for update`)}
	}
	_spec.Node.ID.Value = id
	if fields := auo.fields; len(fields) > 0 {
		_spec.Node.Columns = make([]string, 0, len(fields))
		_spec.Node.Columns = append(_spec.Node.Columns, agent.FieldID)
		for _, f := range fields {
			if !agent.ValidColumn(f) {
				return nil, &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)}
			}
			if f != agent.FieldID {
				_spec.Node.Columns = append(_spec.Node.Columns, f)
			}
		}
	}
	if ps := auo.mutation.predicates; len(ps) > 0 {
		_spec.Predicate = func(selector *sql.Selector) {
			for i := range ps {
				ps[i](selector)
			}
		}
	}
	if value, ok := auo.mutation.UpdatedAt(); ok {
		_spec.SetField(agent.FieldUpdatedAt, field.TypeTime, value)
	}
	if value, ok := auo.mutation.DeletedAt(); ok {
		_spec.SetField(agent.FieldDeletedAt, field.TypeTime, value)
	}
	if auo.mutation.DeletedAtCleared() {
		_spec.ClearField(agent.FieldDeletedAt, field.TypeTime)
	}
	if value, ok := auo.mutation.Name(); ok {
		_spec.SetField(agent.FieldName, field.TypeString, value)
	}
	if value, ok := auo.mutation.Role(); ok {
		_spec.SetField(agent.FieldRole, field.TypeString, value)
	}
	if value, ok := auo.mutation.Status(); ok {
		_spec.SetField(agent.FieldStatus, field.TypeInt, value)
	}
	if value, ok := auo.mutation.AddedStatus(); ok {
		_spec.AddField(agent.FieldStatus, field.TypeInt, value)
	}
	if auo.mutation.StatusCleared() {
		_spec.ClearField(agent.FieldStatus, field.TypeInt)
	}
	if value, ok := auo.mutation.Background(); ok {
		_spec.SetField(agent.FieldBackground, field.TypeString, value)
	}
	if auo.mutation.BackgroundCleared() {
		_spec.ClearField(agent.FieldBackground, field.TypeString)
	}
	if value, ok := auo.mutation.Examples(); ok {
		_spec.SetField(agent.FieldExamples, field.TypeString, value)
	}
	if auo.mutation.ExamplesCleared() {
		_spec.ClearField(agent.FieldExamples, field.TypeString)
	}
	if value, ok := auo.mutation.OrganizationID(); ok {
		_spec.SetField(agent.FieldOrganizationID, field.TypeUint64, value)
	}
	if value, ok := auo.mutation.AddedOrganizationID(); ok {
		_spec.AddField(agent.FieldOrganizationID, field.TypeUint64, value)
	}
	if value, ok := auo.mutation.DatasetID(); ok {
		_spec.SetField(agent.FieldDatasetID, field.TypeString, value)
	}
	if value, ok := auo.mutation.CollectionID(); ok {
		_spec.SetField(agent.FieldCollectionID, field.TypeString, value)
	}
	if auo.mutation.WxAgentCleared() {
		edge := &sqlgraph.EdgeSpec{
			Rel:     sqlgraph.O2M,
			Inverse: false,
			Table:   agent.WxAgentTable,
			Columns: []string{agent.WxAgentColumn},
			Bidi:    false,
			Target: &sqlgraph.EdgeTarget{
				IDSpec: sqlgraph.NewFieldSpec(wx.FieldID, field.TypeUint64),
			},
		}
		_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
	}
	if nodes := auo.mutation.RemovedWxAgentIDs(); len(nodes) > 0 && !auo.mutation.WxAgentCleared() {
		edge := &sqlgraph.EdgeSpec{
			Rel:     sqlgraph.O2M,
			Inverse: false,
			Table:   agent.WxAgentTable,
			Columns: []string{agent.WxAgentColumn},
			Bidi:    false,
			Target: &sqlgraph.EdgeTarget{
				IDSpec: sqlgraph.NewFieldSpec(wx.FieldID, field.TypeUint64),
			},
		}
		for _, k := range nodes {
			edge.Target.Nodes = append(edge.Target.Nodes, k)
		}
		_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
	}
	if nodes := auo.mutation.WxAgentIDs(); len(nodes) > 0 {
		edge := &sqlgraph.EdgeSpec{
			Rel:     sqlgraph.O2M,
			Inverse: false,
			Table:   agent.WxAgentTable,
			Columns: []string{agent.WxAgentColumn},
			Bidi:    false,
			Target: &sqlgraph.EdgeTarget{
				IDSpec: sqlgraph.NewFieldSpec(wx.FieldID, field.TypeUint64),
			},
		}
		for _, k := range nodes {
			edge.Target.Nodes = append(edge.Target.Nodes, k)
		}
		_spec.Edges.Add = append(_spec.Edges.Add, edge)
	}
	if auo.mutation.TokenAgentCleared() {
		edge := &sqlgraph.EdgeSpec{
			Rel:     sqlgraph.O2M,
			Inverse: false,
			Table:   agent.TokenAgentTable,
			Columns: []string{agent.TokenAgentColumn},
			Bidi:    false,
			Target: &sqlgraph.EdgeTarget{
				IDSpec: sqlgraph.NewFieldSpec(token.FieldID, field.TypeUint64),
			},
		}
		_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
	}
	if nodes := auo.mutation.RemovedTokenAgentIDs(); len(nodes) > 0 && !auo.mutation.TokenAgentCleared() {
		edge := &sqlgraph.EdgeSpec{
			Rel:     sqlgraph.O2M,
			Inverse: false,
			Table:   agent.TokenAgentTable,
			Columns: []string{agent.TokenAgentColumn},
			Bidi:    false,
			Target: &sqlgraph.EdgeTarget{
				IDSpec: sqlgraph.NewFieldSpec(token.FieldID, field.TypeUint64),
			},
		}
		for _, k := range nodes {
			edge.Target.Nodes = append(edge.Target.Nodes, k)
		}
		_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
	}
	if nodes := auo.mutation.TokenAgentIDs(); len(nodes) > 0 {
		edge := &sqlgraph.EdgeSpec{
			Rel:     sqlgraph.O2M,
			Inverse: false,
			Table:   agent.TokenAgentTable,
			Columns: []string{agent.TokenAgentColumn},
			Bidi:    false,
			Target: &sqlgraph.EdgeTarget{
				IDSpec: sqlgraph.NewFieldSpec(token.FieldID, field.TypeUint64),
			},
		}
		for _, k := range nodes {
			edge.Target.Nodes = append(edge.Target.Nodes, k)
		}
		_spec.Edges.Add = append(_spec.Edges.Add, edge)
	}
	_node = &Agent{config: auo.config}
	_spec.Assign = _node.assignValues
	_spec.ScanValues = _node.scanValues
	if err = sqlgraph.UpdateNode(ctx, auo.driver, _spec); err != nil {
		if _, ok := err.(*sqlgraph.NotFoundError); ok {
			err = &NotFoundError{agent.Label}
		} else if sqlgraph.IsConstraintError(err) {
			err = &ConstraintError{msg: err.Error(), wrap: err}
		}
		return nil, err
	}
	auo.mutation.done = true
	return _node, nil
}
