// 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/dialect/sql/sqljson"
	"entgo.io/ent/schema/field"
	"github.com/cloudreve/Cloudreve/v4/ent/oauthclient"
	"github.com/cloudreve/Cloudreve/v4/ent/oauthgrant"
	"github.com/cloudreve/Cloudreve/v4/ent/predicate"
	"github.com/cloudreve/Cloudreve/v4/ent/user"
)

// OAuthGrantUpdate is the builder for updating OAuthGrant entities.
type OAuthGrantUpdate struct {
	config
	hooks    []Hook
	mutation *OAuthGrantMutation
}

// Where appends a list predicates to the OAuthGrantUpdate builder.
func (ogu *OAuthGrantUpdate) Where(ps ...predicate.OAuthGrant) *OAuthGrantUpdate {
	ogu.mutation.Where(ps...)
	return ogu
}

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

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

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

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

// SetUserID sets the "user_id" field.
func (ogu *OAuthGrantUpdate) SetUserID(i int) *OAuthGrantUpdate {
	ogu.mutation.SetUserID(i)
	return ogu
}

// SetNillableUserID sets the "user_id" field if the given value is not nil.
func (ogu *OAuthGrantUpdate) SetNillableUserID(i *int) *OAuthGrantUpdate {
	if i != nil {
		ogu.SetUserID(*i)
	}
	return ogu
}

// SetClientID sets the "client_id" field.
func (ogu *OAuthGrantUpdate) SetClientID(i int) *OAuthGrantUpdate {
	ogu.mutation.SetClientID(i)
	return ogu
}

// SetNillableClientID sets the "client_id" field if the given value is not nil.
func (ogu *OAuthGrantUpdate) SetNillableClientID(i *int) *OAuthGrantUpdate {
	if i != nil {
		ogu.SetClientID(*i)
	}
	return ogu
}

// SetScopes sets the "scopes" field.
func (ogu *OAuthGrantUpdate) SetScopes(s []string) *OAuthGrantUpdate {
	ogu.mutation.SetScopes(s)
	return ogu
}

// AppendScopes appends s to the "scopes" field.
func (ogu *OAuthGrantUpdate) AppendScopes(s []string) *OAuthGrantUpdate {
	ogu.mutation.AppendScopes(s)
	return ogu
}

// SetLastUsedAt sets the "last_used_at" field.
func (ogu *OAuthGrantUpdate) SetLastUsedAt(t time.Time) *OAuthGrantUpdate {
	ogu.mutation.SetLastUsedAt(t)
	return ogu
}

// SetNillableLastUsedAt sets the "last_used_at" field if the given value is not nil.
func (ogu *OAuthGrantUpdate) SetNillableLastUsedAt(t *time.Time) *OAuthGrantUpdate {
	if t != nil {
		ogu.SetLastUsedAt(*t)
	}
	return ogu
}

// ClearLastUsedAt clears the value of the "last_used_at" field.
func (ogu *OAuthGrantUpdate) ClearLastUsedAt() *OAuthGrantUpdate {
	ogu.mutation.ClearLastUsedAt()
	return ogu
}

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

// SetClient sets the "client" edge to the OAuthClient entity.
func (ogu *OAuthGrantUpdate) SetClient(o *OAuthClient) *OAuthGrantUpdate {
	return ogu.SetClientID(o.ID)
}

// Mutation returns the OAuthGrantMutation object of the builder.
func (ogu *OAuthGrantUpdate) Mutation() *OAuthGrantMutation {
	return ogu.mutation
}

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

// ClearClient clears the "client" edge to the OAuthClient entity.
func (ogu *OAuthGrantUpdate) ClearClient() *OAuthGrantUpdate {
	ogu.mutation.ClearClient()
	return ogu
}

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

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

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

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

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

// check runs all checks and user-defined validators on the builder.
func (ogu *OAuthGrantUpdate) check() error {
	if _, ok := ogu.mutation.UserID(); ogu.mutation.UserCleared() && !ok {
		return errors.New(`ent: clearing a required unique edge "OAuthGrant.user"`)
	}
	if _, ok := ogu.mutation.ClientID(); ogu.mutation.ClientCleared() && !ok {
		return errors.New(`ent: clearing a required unique edge "OAuthGrant.client"`)
	}
	return nil
}

func (ogu *OAuthGrantUpdate) sqlSave(ctx context.Context) (n int, err error) {
	if err := ogu.check(); err != nil {
		return n, err
	}
	_spec := sqlgraph.NewUpdateSpec(oauthgrant.Table, oauthgrant.Columns, sqlgraph.NewFieldSpec(oauthgrant.FieldID, field.TypeInt))
	if ps := ogu.mutation.predicates; len(ps) > 0 {
		_spec.Predicate = func(selector *sql.Selector) {
			for i := range ps {
				ps[i](selector)
			}
		}
	}
	if value, ok := ogu.mutation.UpdatedAt(); ok {
		_spec.SetField(oauthgrant.FieldUpdatedAt, field.TypeTime, value)
	}
	if value, ok := ogu.mutation.DeletedAt(); ok {
		_spec.SetField(oauthgrant.FieldDeletedAt, field.TypeTime, value)
	}
	if ogu.mutation.DeletedAtCleared() {
		_spec.ClearField(oauthgrant.FieldDeletedAt, field.TypeTime)
	}
	if value, ok := ogu.mutation.Scopes(); ok {
		_spec.SetField(oauthgrant.FieldScopes, field.TypeJSON, value)
	}
	if value, ok := ogu.mutation.AppendedScopes(); ok {
		_spec.AddModifier(func(u *sql.UpdateBuilder) {
			sqljson.Append(u, oauthgrant.FieldScopes, value)
		})
	}
	if value, ok := ogu.mutation.LastUsedAt(); ok {
		_spec.SetField(oauthgrant.FieldLastUsedAt, field.TypeTime, value)
	}
	if ogu.mutation.LastUsedAtCleared() {
		_spec.ClearField(oauthgrant.FieldLastUsedAt, field.TypeTime)
	}
	if ogu.mutation.UserCleared() {
		edge := &sqlgraph.EdgeSpec{
			Rel:     sqlgraph.M2O,
			Inverse: true,
			Table:   oauthgrant.UserTable,
			Columns: []string{oauthgrant.UserColumn},
			Bidi:    false,
			Target: &sqlgraph.EdgeTarget{
				IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeInt),
			},
		}
		_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
	}
	if nodes := ogu.mutation.UserIDs(); len(nodes) > 0 {
		edge := &sqlgraph.EdgeSpec{
			Rel:     sqlgraph.M2O,
			Inverse: true,
			Table:   oauthgrant.UserTable,
			Columns: []string{oauthgrant.UserColumn},
			Bidi:    false,
			Target: &sqlgraph.EdgeTarget{
				IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeInt),
			},
		}
		for _, k := range nodes {
			edge.Target.Nodes = append(edge.Target.Nodes, k)
		}
		_spec.Edges.Add = append(_spec.Edges.Add, edge)
	}
	if ogu.mutation.ClientCleared() {
		edge := &sqlgraph.EdgeSpec{
			Rel:     sqlgraph.M2O,
			Inverse: true,
			Table:   oauthgrant.ClientTable,
			Columns: []string{oauthgrant.ClientColumn},
			Bidi:    false,
			Target: &sqlgraph.EdgeTarget{
				IDSpec: sqlgraph.NewFieldSpec(oauthclient.FieldID, field.TypeInt),
			},
		}
		_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
	}
	if nodes := ogu.mutation.ClientIDs(); len(nodes) > 0 {
		edge := &sqlgraph.EdgeSpec{
			Rel:     sqlgraph.M2O,
			Inverse: true,
			Table:   oauthgrant.ClientTable,
			Columns: []string{oauthgrant.ClientColumn},
			Bidi:    false,
			Target: &sqlgraph.EdgeTarget{
				IDSpec: sqlgraph.NewFieldSpec(oauthclient.FieldID, field.TypeInt),
			},
		}
		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, ogu.driver, _spec); err != nil {
		if _, ok := err.(*sqlgraph.NotFoundError); ok {
			err = &NotFoundError{oauthgrant.Label}
		} else if sqlgraph.IsConstraintError(err) {
			err = &ConstraintError{msg: err.Error(), wrap: err}
		}
		return 0, err
	}
	ogu.mutation.done = true
	return n, nil
}

// OAuthGrantUpdateOne is the builder for updating a single OAuthGrant entity.
type OAuthGrantUpdateOne struct {
	config
	fields   []string
	hooks    []Hook
	mutation *OAuthGrantMutation
}

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

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

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

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

// SetUserID sets the "user_id" field.
func (oguo *OAuthGrantUpdateOne) SetUserID(i int) *OAuthGrantUpdateOne {
	oguo.mutation.SetUserID(i)
	return oguo
}

// SetNillableUserID sets the "user_id" field if the given value is not nil.
func (oguo *OAuthGrantUpdateOne) SetNillableUserID(i *int) *OAuthGrantUpdateOne {
	if i != nil {
		oguo.SetUserID(*i)
	}
	return oguo
}

// SetClientID sets the "client_id" field.
func (oguo *OAuthGrantUpdateOne) SetClientID(i int) *OAuthGrantUpdateOne {
	oguo.mutation.SetClientID(i)
	return oguo
}

// SetNillableClientID sets the "client_id" field if the given value is not nil.
func (oguo *OAuthGrantUpdateOne) SetNillableClientID(i *int) *OAuthGrantUpdateOne {
	if i != nil {
		oguo.SetClientID(*i)
	}
	return oguo
}

// SetScopes sets the "scopes" field.
func (oguo *OAuthGrantUpdateOne) SetScopes(s []string) *OAuthGrantUpdateOne {
	oguo.mutation.SetScopes(s)
	return oguo
}

// AppendScopes appends s to the "scopes" field.
func (oguo *OAuthGrantUpdateOne) AppendScopes(s []string) *OAuthGrantUpdateOne {
	oguo.mutation.AppendScopes(s)
	return oguo
}

// SetLastUsedAt sets the "last_used_at" field.
func (oguo *OAuthGrantUpdateOne) SetLastUsedAt(t time.Time) *OAuthGrantUpdateOne {
	oguo.mutation.SetLastUsedAt(t)
	return oguo
}

// SetNillableLastUsedAt sets the "last_used_at" field if the given value is not nil.
func (oguo *OAuthGrantUpdateOne) SetNillableLastUsedAt(t *time.Time) *OAuthGrantUpdateOne {
	if t != nil {
		oguo.SetLastUsedAt(*t)
	}
	return oguo
}

// ClearLastUsedAt clears the value of the "last_used_at" field.
func (oguo *OAuthGrantUpdateOne) ClearLastUsedAt() *OAuthGrantUpdateOne {
	oguo.mutation.ClearLastUsedAt()
	return oguo
}

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

// SetClient sets the "client" edge to the OAuthClient entity.
func (oguo *OAuthGrantUpdateOne) SetClient(o *OAuthClient) *OAuthGrantUpdateOne {
	return oguo.SetClientID(o.ID)
}

// Mutation returns the OAuthGrantMutation object of the builder.
func (oguo *OAuthGrantUpdateOne) Mutation() *OAuthGrantMutation {
	return oguo.mutation
}

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

// ClearClient clears the "client" edge to the OAuthClient entity.
func (oguo *OAuthGrantUpdateOne) ClearClient() *OAuthGrantUpdateOne {
	oguo.mutation.ClearClient()
	return oguo
}

// Where appends a list predicates to the OAuthGrantUpdate builder.
func (oguo *OAuthGrantUpdateOne) Where(ps ...predicate.OAuthGrant) *OAuthGrantUpdateOne {
	oguo.mutation.Where(ps...)
	return oguo
}

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

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

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

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

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

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

// check runs all checks and user-defined validators on the builder.
func (oguo *OAuthGrantUpdateOne) check() error {
	if _, ok := oguo.mutation.UserID(); oguo.mutation.UserCleared() && !ok {
		return errors.New(`ent: clearing a required unique edge "OAuthGrant.user"`)
	}
	if _, ok := oguo.mutation.ClientID(); oguo.mutation.ClientCleared() && !ok {
		return errors.New(`ent: clearing a required unique edge "OAuthGrant.client"`)
	}
	return nil
}

func (oguo *OAuthGrantUpdateOne) sqlSave(ctx context.Context) (_node *OAuthGrant, err error) {
	if err := oguo.check(); err != nil {
		return _node, err
	}
	_spec := sqlgraph.NewUpdateSpec(oauthgrant.Table, oauthgrant.Columns, sqlgraph.NewFieldSpec(oauthgrant.FieldID, field.TypeInt))
	id, ok := oguo.mutation.ID()
	if !ok {
		return nil, &ValidationError{Name: "id", err: errors.New(`ent: missing "OAuthGrant.id" for update`)}
	}
	_spec.Node.ID.Value = id
	if fields := oguo.fields; len(fields) > 0 {
		_spec.Node.Columns = make([]string, 0, len(fields))
		_spec.Node.Columns = append(_spec.Node.Columns, oauthgrant.FieldID)
		for _, f := range fields {
			if !oauthgrant.ValidColumn(f) {
				return nil, &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)}
			}
			if f != oauthgrant.FieldID {
				_spec.Node.Columns = append(_spec.Node.Columns, f)
			}
		}
	}
	if ps := oguo.mutation.predicates; len(ps) > 0 {
		_spec.Predicate = func(selector *sql.Selector) {
			for i := range ps {
				ps[i](selector)
			}
		}
	}
	if value, ok := oguo.mutation.UpdatedAt(); ok {
		_spec.SetField(oauthgrant.FieldUpdatedAt, field.TypeTime, value)
	}
	if value, ok := oguo.mutation.DeletedAt(); ok {
		_spec.SetField(oauthgrant.FieldDeletedAt, field.TypeTime, value)
	}
	if oguo.mutation.DeletedAtCleared() {
		_spec.ClearField(oauthgrant.FieldDeletedAt, field.TypeTime)
	}
	if value, ok := oguo.mutation.Scopes(); ok {
		_spec.SetField(oauthgrant.FieldScopes, field.TypeJSON, value)
	}
	if value, ok := oguo.mutation.AppendedScopes(); ok {
		_spec.AddModifier(func(u *sql.UpdateBuilder) {
			sqljson.Append(u, oauthgrant.FieldScopes, value)
		})
	}
	if value, ok := oguo.mutation.LastUsedAt(); ok {
		_spec.SetField(oauthgrant.FieldLastUsedAt, field.TypeTime, value)
	}
	if oguo.mutation.LastUsedAtCleared() {
		_spec.ClearField(oauthgrant.FieldLastUsedAt, field.TypeTime)
	}
	if oguo.mutation.UserCleared() {
		edge := &sqlgraph.EdgeSpec{
			Rel:     sqlgraph.M2O,
			Inverse: true,
			Table:   oauthgrant.UserTable,
			Columns: []string{oauthgrant.UserColumn},
			Bidi:    false,
			Target: &sqlgraph.EdgeTarget{
				IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeInt),
			},
		}
		_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
	}
	if nodes := oguo.mutation.UserIDs(); len(nodes) > 0 {
		edge := &sqlgraph.EdgeSpec{
			Rel:     sqlgraph.M2O,
			Inverse: true,
			Table:   oauthgrant.UserTable,
			Columns: []string{oauthgrant.UserColumn},
			Bidi:    false,
			Target: &sqlgraph.EdgeTarget{
				IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeInt),
			},
		}
		for _, k := range nodes {
			edge.Target.Nodes = append(edge.Target.Nodes, k)
		}
		_spec.Edges.Add = append(_spec.Edges.Add, edge)
	}
	if oguo.mutation.ClientCleared() {
		edge := &sqlgraph.EdgeSpec{
			Rel:     sqlgraph.M2O,
			Inverse: true,
			Table:   oauthgrant.ClientTable,
			Columns: []string{oauthgrant.ClientColumn},
			Bidi:    false,
			Target: &sqlgraph.EdgeTarget{
				IDSpec: sqlgraph.NewFieldSpec(oauthclient.FieldID, field.TypeInt),
			},
		}
		_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
	}
	if nodes := oguo.mutation.ClientIDs(); len(nodes) > 0 {
		edge := &sqlgraph.EdgeSpec{
			Rel:     sqlgraph.M2O,
			Inverse: true,
			Table:   oauthgrant.ClientTable,
			Columns: []string{oauthgrant.ClientColumn},
			Bidi:    false,
			Target: &sqlgraph.EdgeTarget{
				IDSpec: sqlgraph.NewFieldSpec(oauthclient.FieldID, field.TypeInt),
			},
		}
		for _, k := range nodes {
			edge.Target.Nodes = append(edge.Target.Nodes, k)
		}
		_spec.Edges.Add = append(_spec.Edges.Add, edge)
	}
	_node = &OAuthGrant{config: oguo.config}
	_spec.Assign = _node.assignValues
	_spec.ScanValues = _node.scanValues
	if err = sqlgraph.UpdateNode(ctx, oguo.driver, _spec); err != nil {
		if _, ok := err.(*sqlgraph.NotFoundError); ok {
			err = &NotFoundError{oauthgrant.Label}
		} else if sqlgraph.IsConstraintError(err) {
			err = &ConstraintError{msg: err.Error(), wrap: err}
		}
		return nil, err
	}
	oguo.mutation.done = true
	return _node, nil
}
