// Code generated by ent, DO NOT EDIT.

package ent

import (
	"context"
	"errors"
	"fmt"
	"time"

	"entgo.io/ent/dialect/sql"
	"entgo.io/ent/dialect/sql/sqlgraph"
	"entgo.io/ent/schema/field"
	"git.noahlan.cn/n-admin/n-admin-server/rpc/core/ent/predicate"
	"git.noahlan.cn/n-admin/n-admin-server/rpc/core/ent/token"
	"git.noahlan.cn/n-admin/n-admin-server/rpc/core/ent/user"
	"git.noahlan.cn/noahlan/ntool-biz/core/orm/nent/types"
)

// TokenUpdate is the builder for updating Token entities.
type TokenUpdate struct {
	config
	hooks     []Hook
	mutation  *TokenMutation
	modifiers []func(*sql.UpdateBuilder)
}

// Where appends a list predicates to the TokenUpdate builder.
func (tu *TokenUpdate) Where(ps ...predicate.Token) *TokenUpdate {
	tu.mutation.Where(ps...)
	return tu
}

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

// SetStatus sets the "status" field.
func (tu *TokenUpdate) SetStatus(t types.Status) *TokenUpdate {
	tu.mutation.SetStatus(t)
	return tu
}

// SetNillableStatus sets the "status" field if the given value is not nil.
func (tu *TokenUpdate) SetNillableStatus(t *types.Status) *TokenUpdate {
	if t != nil {
		tu.SetStatus(*t)
	}
	return tu
}

// SetVersion sets the "version" field.
func (tu *TokenUpdate) SetVersion(i int64) *TokenUpdate {
	tu.mutation.ResetVersion()
	tu.mutation.SetVersion(i)
	return tu
}

// SetNillableVersion sets the "version" field if the given value is not nil.
func (tu *TokenUpdate) SetNillableVersion(i *int64) *TokenUpdate {
	if i != nil {
		tu.SetVersion(*i)
	}
	return tu
}

// AddVersion adds i to the "version" field.
func (tu *TokenUpdate) AddVersion(i int64) *TokenUpdate {
	tu.mutation.AddVersion(i)
	return tu
}

// SetUserID sets the "user_id" field.
func (tu *TokenUpdate) SetUserID(i int64) *TokenUpdate {
	tu.mutation.SetUserID(i)
	return tu
}

// SetTokenType sets the "token_type" field.
func (tu *TokenUpdate) SetTokenType(s string) *TokenUpdate {
	tu.mutation.SetTokenType(s)
	return tu
}

// SetAccessToken sets the "access_token" field.
func (tu *TokenUpdate) SetAccessToken(s string) *TokenUpdate {
	tu.mutation.SetAccessToken(s)
	return tu
}

// SetRefreshToken sets the "refresh_token" field.
func (tu *TokenUpdate) SetRefreshToken(s string) *TokenUpdate {
	tu.mutation.SetRefreshToken(s)
	return tu
}

// SetSource sets the "source" field.
func (tu *TokenUpdate) SetSource(s string) *TokenUpdate {
	tu.mutation.SetSource(s)
	return tu
}

// SetExpiredAt sets the "expired_at" field.
func (tu *TokenUpdate) SetExpiredAt(t time.Time) *TokenUpdate {
	tu.mutation.SetExpiredAt(t)
	return tu
}

// SetUser sets the "user" edge to the User entity.
func (tu *TokenUpdate) SetUser(u *User) *TokenUpdate {
	return tu.SetUserID(u.ID)
}

// Mutation returns the TokenMutation object of the builder.
func (tu *TokenUpdate) Mutation() *TokenMutation {
	return tu.mutation
}

// ClearUser clears the "user" edge to the User entity.
func (tu *TokenUpdate) ClearUser() *TokenUpdate {
	tu.mutation.ClearUser()
	return tu
}

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

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

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

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

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

// check runs all checks and user-defined validators on the builder.
func (tu *TokenUpdate) check() error {
	if v, ok := tu.mutation.Status(); ok {
		if err := token.StatusValidator(v); err != nil {
			return &ValidationError{Name: "status", err: fmt.Errorf(`ent: validator failed for field "Token.status": %w`, err)}
		}
	}
	if _, ok := tu.mutation.UserID(); tu.mutation.UserCleared() && !ok {
		return errors.New(`ent: clearing a required unique edge "Token.user"`)
	}
	return nil
}

// Modify adds a statement modifier for attaching custom logic to the UPDATE statement.
func (tu *TokenUpdate) Modify(modifiers ...func(u *sql.UpdateBuilder)) *TokenUpdate {
	tu.modifiers = append(tu.modifiers, modifiers...)
	return tu
}

func (tu *TokenUpdate) sqlSave(ctx context.Context) (n int, err error) {
	if err := tu.check(); err != nil {
		return n, err
	}
	_spec := sqlgraph.NewUpdateSpec(token.Table, token.Columns, sqlgraph.NewFieldSpec(token.FieldID, field.TypeInt64))
	if ps := tu.mutation.predicates; len(ps) > 0 {
		_spec.Predicate = func(selector *sql.Selector) {
			for i := range ps {
				ps[i](selector)
			}
		}
	}
	if value, ok := tu.mutation.UpdatedAt(); ok {
		_spec.SetField(token.FieldUpdatedAt, field.TypeTime, value)
	}
	if value, ok := tu.mutation.Status(); ok {
		_spec.SetField(token.FieldStatus, field.TypeEnum, value)
	}
	if value, ok := tu.mutation.Version(); ok {
		_spec.SetField(token.FieldVersion, field.TypeInt64, value)
	}
	if value, ok := tu.mutation.AddedVersion(); ok {
		_spec.AddField(token.FieldVersion, field.TypeInt64, value)
	}
	if value, ok := tu.mutation.TokenType(); ok {
		_spec.SetField(token.FieldTokenType, field.TypeString, value)
	}
	if value, ok := tu.mutation.AccessToken(); ok {
		_spec.SetField(token.FieldAccessToken, field.TypeString, value)
	}
	if value, ok := tu.mutation.RefreshToken(); ok {
		_spec.SetField(token.FieldRefreshToken, field.TypeString, value)
	}
	if value, ok := tu.mutation.Source(); ok {
		_spec.SetField(token.FieldSource, field.TypeString, value)
	}
	if value, ok := tu.mutation.ExpiredAt(); ok {
		_spec.SetField(token.FieldExpiredAt, field.TypeTime, value)
	}
	if tu.mutation.UserCleared() {
		edge := &sqlgraph.EdgeSpec{
			Rel:     sqlgraph.M2O,
			Inverse: true,
			Table:   token.UserTable,
			Columns: []string{token.UserColumn},
			Bidi:    false,
			Target: &sqlgraph.EdgeTarget{
				IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeInt64),
			},
		}
		_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
	}
	if nodes := tu.mutation.UserIDs(); len(nodes) > 0 {
		edge := &sqlgraph.EdgeSpec{
			Rel:     sqlgraph.M2O,
			Inverse: true,
			Table:   token.UserTable,
			Columns: []string{token.UserColumn},
			Bidi:    false,
			Target: &sqlgraph.EdgeTarget{
				IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeInt64),
			},
		}
		for _, k := range nodes {
			edge.Target.Nodes = append(edge.Target.Nodes, k)
		}
		_spec.Edges.Add = append(_spec.Edges.Add, edge)
	}
	_spec.AddModifiers(tu.modifiers...)
	if n, err = sqlgraph.UpdateNodes(ctx, tu.driver, _spec); err != nil {
		if _, ok := err.(*sqlgraph.NotFoundError); ok {
			err = &NotFoundError{token.Label}
		} else if sqlgraph.IsConstraintError(err) {
			err = &ConstraintError{msg: err.Error(), wrap: err}
		}
		return 0, err
	}
	tu.mutation.done = true
	return n, nil
}

// TokenUpdateOne is the builder for updating a single Token entity.
type TokenUpdateOne struct {
	config
	fields    []string
	hooks     []Hook
	mutation  *TokenMutation
	modifiers []func(*sql.UpdateBuilder)
}

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

// SetStatus sets the "status" field.
func (tuo *TokenUpdateOne) SetStatus(t types.Status) *TokenUpdateOne {
	tuo.mutation.SetStatus(t)
	return tuo
}

// SetNillableStatus sets the "status" field if the given value is not nil.
func (tuo *TokenUpdateOne) SetNillableStatus(t *types.Status) *TokenUpdateOne {
	if t != nil {
		tuo.SetStatus(*t)
	}
	return tuo
}

// SetVersion sets the "version" field.
func (tuo *TokenUpdateOne) SetVersion(i int64) *TokenUpdateOne {
	tuo.mutation.ResetVersion()
	tuo.mutation.SetVersion(i)
	return tuo
}

// SetNillableVersion sets the "version" field if the given value is not nil.
func (tuo *TokenUpdateOne) SetNillableVersion(i *int64) *TokenUpdateOne {
	if i != nil {
		tuo.SetVersion(*i)
	}
	return tuo
}

// AddVersion adds i to the "version" field.
func (tuo *TokenUpdateOne) AddVersion(i int64) *TokenUpdateOne {
	tuo.mutation.AddVersion(i)
	return tuo
}

// SetUserID sets the "user_id" field.
func (tuo *TokenUpdateOne) SetUserID(i int64) *TokenUpdateOne {
	tuo.mutation.SetUserID(i)
	return tuo
}

// SetTokenType sets the "token_type" field.
func (tuo *TokenUpdateOne) SetTokenType(s string) *TokenUpdateOne {
	tuo.mutation.SetTokenType(s)
	return tuo
}

// SetAccessToken sets the "access_token" field.
func (tuo *TokenUpdateOne) SetAccessToken(s string) *TokenUpdateOne {
	tuo.mutation.SetAccessToken(s)
	return tuo
}

// SetRefreshToken sets the "refresh_token" field.
func (tuo *TokenUpdateOne) SetRefreshToken(s string) *TokenUpdateOne {
	tuo.mutation.SetRefreshToken(s)
	return tuo
}

// SetSource sets the "source" field.
func (tuo *TokenUpdateOne) SetSource(s string) *TokenUpdateOne {
	tuo.mutation.SetSource(s)
	return tuo
}

// SetExpiredAt sets the "expired_at" field.
func (tuo *TokenUpdateOne) SetExpiredAt(t time.Time) *TokenUpdateOne {
	tuo.mutation.SetExpiredAt(t)
	return tuo
}

// SetUser sets the "user" edge to the User entity.
func (tuo *TokenUpdateOne) SetUser(u *User) *TokenUpdateOne {
	return tuo.SetUserID(u.ID)
}

// Mutation returns the TokenMutation object of the builder.
func (tuo *TokenUpdateOne) Mutation() *TokenMutation {
	return tuo.mutation
}

// ClearUser clears the "user" edge to the User entity.
func (tuo *TokenUpdateOne) ClearUser() *TokenUpdateOne {
	tuo.mutation.ClearUser()
	return tuo
}

// Where appends a list predicates to the TokenUpdate builder.
func (tuo *TokenUpdateOne) Where(ps ...predicate.Token) *TokenUpdateOne {
	tuo.mutation.Where(ps...)
	return tuo
}

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

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

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

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

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

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

// check runs all checks and user-defined validators on the builder.
func (tuo *TokenUpdateOne) check() error {
	if v, ok := tuo.mutation.Status(); ok {
		if err := token.StatusValidator(v); err != nil {
			return &ValidationError{Name: "status", err: fmt.Errorf(`ent: validator failed for field "Token.status": %w`, err)}
		}
	}
	if _, ok := tuo.mutation.UserID(); tuo.mutation.UserCleared() && !ok {
		return errors.New(`ent: clearing a required unique edge "Token.user"`)
	}
	return nil
}

// Modify adds a statement modifier for attaching custom logic to the UPDATE statement.
func (tuo *TokenUpdateOne) Modify(modifiers ...func(u *sql.UpdateBuilder)) *TokenUpdateOne {
	tuo.modifiers = append(tuo.modifiers, modifiers...)
	return tuo
}

func (tuo *TokenUpdateOne) sqlSave(ctx context.Context) (_node *Token, err error) {
	if err := tuo.check(); err != nil {
		return _node, err
	}
	_spec := sqlgraph.NewUpdateSpec(token.Table, token.Columns, sqlgraph.NewFieldSpec(token.FieldID, field.TypeInt64))
	id, ok := tuo.mutation.ID()
	if !ok {
		return nil, &ValidationError{Name: "id", err: errors.New(`ent: missing "Token.id" for update`)}
	}
	_spec.Node.ID.Value = id
	if fields := tuo.fields; len(fields) > 0 {
		_spec.Node.Columns = make([]string, 0, len(fields))
		_spec.Node.Columns = append(_spec.Node.Columns, token.FieldID)
		for _, f := range fields {
			if !token.ValidColumn(f) {
				return nil, &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)}
			}
			if f != token.FieldID {
				_spec.Node.Columns = append(_spec.Node.Columns, f)
			}
		}
	}
	if ps := tuo.mutation.predicates; len(ps) > 0 {
		_spec.Predicate = func(selector *sql.Selector) {
			for i := range ps {
				ps[i](selector)
			}
		}
	}
	if value, ok := tuo.mutation.UpdatedAt(); ok {
		_spec.SetField(token.FieldUpdatedAt, field.TypeTime, value)
	}
	if value, ok := tuo.mutation.Status(); ok {
		_spec.SetField(token.FieldStatus, field.TypeEnum, value)
	}
	if value, ok := tuo.mutation.Version(); ok {
		_spec.SetField(token.FieldVersion, field.TypeInt64, value)
	}
	if value, ok := tuo.mutation.AddedVersion(); ok {
		_spec.AddField(token.FieldVersion, field.TypeInt64, value)
	}
	if value, ok := tuo.mutation.TokenType(); ok {
		_spec.SetField(token.FieldTokenType, field.TypeString, value)
	}
	if value, ok := tuo.mutation.AccessToken(); ok {
		_spec.SetField(token.FieldAccessToken, field.TypeString, value)
	}
	if value, ok := tuo.mutation.RefreshToken(); ok {
		_spec.SetField(token.FieldRefreshToken, field.TypeString, value)
	}
	if value, ok := tuo.mutation.Source(); ok {
		_spec.SetField(token.FieldSource, field.TypeString, value)
	}
	if value, ok := tuo.mutation.ExpiredAt(); ok {
		_spec.SetField(token.FieldExpiredAt, field.TypeTime, value)
	}
	if tuo.mutation.UserCleared() {
		edge := &sqlgraph.EdgeSpec{
			Rel:     sqlgraph.M2O,
			Inverse: true,
			Table:   token.UserTable,
			Columns: []string{token.UserColumn},
			Bidi:    false,
			Target: &sqlgraph.EdgeTarget{
				IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeInt64),
			},
		}
		_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
	}
	if nodes := tuo.mutation.UserIDs(); len(nodes) > 0 {
		edge := &sqlgraph.EdgeSpec{
			Rel:     sqlgraph.M2O,
			Inverse: true,
			Table:   token.UserTable,
			Columns: []string{token.UserColumn},
			Bidi:    false,
			Target: &sqlgraph.EdgeTarget{
				IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeInt64),
			},
		}
		for _, k := range nodes {
			edge.Target.Nodes = append(edge.Target.Nodes, k)
		}
		_spec.Edges.Add = append(_spec.Edges.Add, edge)
	}
	_spec.AddModifiers(tuo.modifiers...)
	_node = &Token{config: tuo.config}
	_spec.Assign = _node.assignValues
	_spec.ScanValues = _node.scanValues
	if err = sqlgraph.UpdateNode(ctx, tuo.driver, _spec); err != nil {
		if _, ok := err.(*sqlgraph.NotFoundError); ok {
			err = &NotFoundError{token.Label}
		} else if sqlgraph.IsConstraintError(err) {
			err = &ConstraintError{msg: err.Error(), wrap: err}
		}
		return nil, err
	}
	tuo.mutation.done = true
	return _node, nil
}
