// Code generated by ent, DO NOT EDIT.

package db

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

	"entgo.io/ent/dialect/sql"
	"entgo.io/ent/dialect/sql/sqlgraph"
	"entgo.io/ent/schema/field"
	"github.com/chaitin/MonkeyCode/backend/db/modelprovider"
	"github.com/chaitin/MonkeyCode/backend/db/modelprovidermodel"
	"github.com/chaitin/MonkeyCode/backend/db/predicate"
	"github.com/google/uuid"
)

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

// Where appends a list predicates to the ModelProviderUpdate builder.
func (mpu *ModelProviderUpdate) Where(ps ...predicate.ModelProvider) *ModelProviderUpdate {
	mpu.mutation.Where(ps...)
	return mpu
}

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

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

// SetAPIBase sets the "api_base" field.
func (mpu *ModelProviderUpdate) SetAPIBase(s string) *ModelProviderUpdate {
	mpu.mutation.SetAPIBase(s)
	return mpu
}

// SetNillableAPIBase sets the "api_base" field if the given value is not nil.
func (mpu *ModelProviderUpdate) SetNillableAPIBase(s *string) *ModelProviderUpdate {
	if s != nil {
		mpu.SetAPIBase(*s)
	}
	return mpu
}

// SetPriority sets the "priority" field.
func (mpu *ModelProviderUpdate) SetPriority(i int) *ModelProviderUpdate {
	mpu.mutation.ResetPriority()
	mpu.mutation.SetPriority(i)
	return mpu
}

// SetNillablePriority sets the "priority" field if the given value is not nil.
func (mpu *ModelProviderUpdate) SetNillablePriority(i *int) *ModelProviderUpdate {
	if i != nil {
		mpu.SetPriority(*i)
	}
	return mpu
}

// AddPriority adds i to the "priority" field.
func (mpu *ModelProviderUpdate) AddPriority(i int) *ModelProviderUpdate {
	mpu.mutation.AddPriority(i)
	return mpu
}

// SetCreatedAt sets the "created_at" field.
func (mpu *ModelProviderUpdate) SetCreatedAt(t time.Time) *ModelProviderUpdate {
	mpu.mutation.SetCreatedAt(t)
	return mpu
}

// SetNillableCreatedAt sets the "created_at" field if the given value is not nil.
func (mpu *ModelProviderUpdate) SetNillableCreatedAt(t *time.Time) *ModelProviderUpdate {
	if t != nil {
		mpu.SetCreatedAt(*t)
	}
	return mpu
}

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

// AddModelIDs adds the "models" edge to the ModelProviderModel entity by IDs.
func (mpu *ModelProviderUpdate) AddModelIDs(ids ...uuid.UUID) *ModelProviderUpdate {
	mpu.mutation.AddModelIDs(ids...)
	return mpu
}

// AddModels adds the "models" edges to the ModelProviderModel entity.
func (mpu *ModelProviderUpdate) AddModels(m ...*ModelProviderModel) *ModelProviderUpdate {
	ids := make([]uuid.UUID, len(m))
	for i := range m {
		ids[i] = m[i].ID
	}
	return mpu.AddModelIDs(ids...)
}

// Mutation returns the ModelProviderMutation object of the builder.
func (mpu *ModelProviderUpdate) Mutation() *ModelProviderMutation {
	return mpu.mutation
}

// ClearModels clears all "models" edges to the ModelProviderModel entity.
func (mpu *ModelProviderUpdate) ClearModels() *ModelProviderUpdate {
	mpu.mutation.ClearModels()
	return mpu
}

// RemoveModelIDs removes the "models" edge to ModelProviderModel entities by IDs.
func (mpu *ModelProviderUpdate) RemoveModelIDs(ids ...uuid.UUID) *ModelProviderUpdate {
	mpu.mutation.RemoveModelIDs(ids...)
	return mpu
}

// RemoveModels removes "models" edges to ModelProviderModel entities.
func (mpu *ModelProviderUpdate) RemoveModels(m ...*ModelProviderModel) *ModelProviderUpdate {
	ids := make([]uuid.UUID, len(m))
	for i := range m {
		ids[i] = m[i].ID
	}
	return mpu.RemoveModelIDs(ids...)
}

// Save executes the query and returns the number of nodes affected by the update operation.
func (mpu *ModelProviderUpdate) Save(ctx context.Context) (int, error) {
	mpu.defaults()
	return withHooks(ctx, mpu.sqlSave, mpu.mutation, mpu.hooks)
}

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

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

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

// defaults sets the default values of the builder before save.
func (mpu *ModelProviderUpdate) defaults() {
	if _, ok := mpu.mutation.UpdatedAt(); !ok {
		v := modelprovider.UpdateDefaultUpdatedAt()
		mpu.mutation.SetUpdatedAt(v)
	}
}

// check runs all checks and user-defined validators on the builder.
func (mpu *ModelProviderUpdate) check() error {
	if v, ok := mpu.mutation.Name(); ok {
		if err := modelprovider.NameValidator(v); err != nil {
			return &ValidationError{Name: "name", err: fmt.Errorf(`db: validator failed for field "ModelProvider.name": %w`, err)}
		}
	}
	if v, ok := mpu.mutation.APIBase(); ok {
		if err := modelprovider.APIBaseValidator(v); err != nil {
			return &ValidationError{Name: "api_base", err: fmt.Errorf(`db: validator failed for field "ModelProvider.api_base": %w`, err)}
		}
	}
	return nil
}

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

func (mpu *ModelProviderUpdate) sqlSave(ctx context.Context) (n int, err error) {
	if err := mpu.check(); err != nil {
		return n, err
	}
	_spec := sqlgraph.NewUpdateSpec(modelprovider.Table, modelprovider.Columns, sqlgraph.NewFieldSpec(modelprovider.FieldID, field.TypeString))
	if ps := mpu.mutation.predicates; len(ps) > 0 {
		_spec.Predicate = func(selector *sql.Selector) {
			for i := range ps {
				ps[i](selector)
			}
		}
	}
	if value, ok := mpu.mutation.Name(); ok {
		_spec.SetField(modelprovider.FieldName, field.TypeString, value)
	}
	if value, ok := mpu.mutation.APIBase(); ok {
		_spec.SetField(modelprovider.FieldAPIBase, field.TypeString, value)
	}
	if value, ok := mpu.mutation.Priority(); ok {
		_spec.SetField(modelprovider.FieldPriority, field.TypeInt, value)
	}
	if value, ok := mpu.mutation.AddedPriority(); ok {
		_spec.AddField(modelprovider.FieldPriority, field.TypeInt, value)
	}
	if value, ok := mpu.mutation.CreatedAt(); ok {
		_spec.SetField(modelprovider.FieldCreatedAt, field.TypeTime, value)
	}
	if value, ok := mpu.mutation.UpdatedAt(); ok {
		_spec.SetField(modelprovider.FieldUpdatedAt, field.TypeTime, value)
	}
	if mpu.mutation.ModelsCleared() {
		edge := &sqlgraph.EdgeSpec{
			Rel:     sqlgraph.O2M,
			Inverse: false,
			Table:   modelprovider.ModelsTable,
			Columns: []string{modelprovider.ModelsColumn},
			Bidi:    false,
			Target: &sqlgraph.EdgeTarget{
				IDSpec: sqlgraph.NewFieldSpec(modelprovidermodel.FieldID, field.TypeUUID),
			},
		}
		_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
	}
	if nodes := mpu.mutation.RemovedModelsIDs(); len(nodes) > 0 && !mpu.mutation.ModelsCleared() {
		edge := &sqlgraph.EdgeSpec{
			Rel:     sqlgraph.O2M,
			Inverse: false,
			Table:   modelprovider.ModelsTable,
			Columns: []string{modelprovider.ModelsColumn},
			Bidi:    false,
			Target: &sqlgraph.EdgeTarget{
				IDSpec: sqlgraph.NewFieldSpec(modelprovidermodel.FieldID, field.TypeUUID),
			},
		}
		for _, k := range nodes {
			edge.Target.Nodes = append(edge.Target.Nodes, k)
		}
		_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
	}
	if nodes := mpu.mutation.ModelsIDs(); len(nodes) > 0 {
		edge := &sqlgraph.EdgeSpec{
			Rel:     sqlgraph.O2M,
			Inverse: false,
			Table:   modelprovider.ModelsTable,
			Columns: []string{modelprovider.ModelsColumn},
			Bidi:    false,
			Target: &sqlgraph.EdgeTarget{
				IDSpec: sqlgraph.NewFieldSpec(modelprovidermodel.FieldID, field.TypeUUID),
			},
		}
		for _, k := range nodes {
			edge.Target.Nodes = append(edge.Target.Nodes, k)
		}
		_spec.Edges.Add = append(_spec.Edges.Add, edge)
	}
	_spec.AddModifiers(mpu.modifiers...)
	if n, err = sqlgraph.UpdateNodes(ctx, mpu.driver, _spec); err != nil {
		if _, ok := err.(*sqlgraph.NotFoundError); ok {
			err = &NotFoundError{modelprovider.Label}
		} else if sqlgraph.IsConstraintError(err) {
			err = &ConstraintError{msg: err.Error(), wrap: err}
		}
		return 0, err
	}
	mpu.mutation.done = true
	return n, nil
}

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

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

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

// SetAPIBase sets the "api_base" field.
func (mpuo *ModelProviderUpdateOne) SetAPIBase(s string) *ModelProviderUpdateOne {
	mpuo.mutation.SetAPIBase(s)
	return mpuo
}

// SetNillableAPIBase sets the "api_base" field if the given value is not nil.
func (mpuo *ModelProviderUpdateOne) SetNillableAPIBase(s *string) *ModelProviderUpdateOne {
	if s != nil {
		mpuo.SetAPIBase(*s)
	}
	return mpuo
}

// SetPriority sets the "priority" field.
func (mpuo *ModelProviderUpdateOne) SetPriority(i int) *ModelProviderUpdateOne {
	mpuo.mutation.ResetPriority()
	mpuo.mutation.SetPriority(i)
	return mpuo
}

// SetNillablePriority sets the "priority" field if the given value is not nil.
func (mpuo *ModelProviderUpdateOne) SetNillablePriority(i *int) *ModelProviderUpdateOne {
	if i != nil {
		mpuo.SetPriority(*i)
	}
	return mpuo
}

// AddPriority adds i to the "priority" field.
func (mpuo *ModelProviderUpdateOne) AddPriority(i int) *ModelProviderUpdateOne {
	mpuo.mutation.AddPriority(i)
	return mpuo
}

// SetCreatedAt sets the "created_at" field.
func (mpuo *ModelProviderUpdateOne) SetCreatedAt(t time.Time) *ModelProviderUpdateOne {
	mpuo.mutation.SetCreatedAt(t)
	return mpuo
}

// SetNillableCreatedAt sets the "created_at" field if the given value is not nil.
func (mpuo *ModelProviderUpdateOne) SetNillableCreatedAt(t *time.Time) *ModelProviderUpdateOne {
	if t != nil {
		mpuo.SetCreatedAt(*t)
	}
	return mpuo
}

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

// AddModelIDs adds the "models" edge to the ModelProviderModel entity by IDs.
func (mpuo *ModelProviderUpdateOne) AddModelIDs(ids ...uuid.UUID) *ModelProviderUpdateOne {
	mpuo.mutation.AddModelIDs(ids...)
	return mpuo
}

// AddModels adds the "models" edges to the ModelProviderModel entity.
func (mpuo *ModelProviderUpdateOne) AddModels(m ...*ModelProviderModel) *ModelProviderUpdateOne {
	ids := make([]uuid.UUID, len(m))
	for i := range m {
		ids[i] = m[i].ID
	}
	return mpuo.AddModelIDs(ids...)
}

// Mutation returns the ModelProviderMutation object of the builder.
func (mpuo *ModelProviderUpdateOne) Mutation() *ModelProviderMutation {
	return mpuo.mutation
}

// ClearModels clears all "models" edges to the ModelProviderModel entity.
func (mpuo *ModelProviderUpdateOne) ClearModels() *ModelProviderUpdateOne {
	mpuo.mutation.ClearModels()
	return mpuo
}

// RemoveModelIDs removes the "models" edge to ModelProviderModel entities by IDs.
func (mpuo *ModelProviderUpdateOne) RemoveModelIDs(ids ...uuid.UUID) *ModelProviderUpdateOne {
	mpuo.mutation.RemoveModelIDs(ids...)
	return mpuo
}

// RemoveModels removes "models" edges to ModelProviderModel entities.
func (mpuo *ModelProviderUpdateOne) RemoveModels(m ...*ModelProviderModel) *ModelProviderUpdateOne {
	ids := make([]uuid.UUID, len(m))
	for i := range m {
		ids[i] = m[i].ID
	}
	return mpuo.RemoveModelIDs(ids...)
}

// Where appends a list predicates to the ModelProviderUpdate builder.
func (mpuo *ModelProviderUpdateOne) Where(ps ...predicate.ModelProvider) *ModelProviderUpdateOne {
	mpuo.mutation.Where(ps...)
	return mpuo
}

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

// Save executes the query and returns the updated ModelProvider entity.
func (mpuo *ModelProviderUpdateOne) Save(ctx context.Context) (*ModelProvider, error) {
	mpuo.defaults()
	return withHooks(ctx, mpuo.sqlSave, mpuo.mutation, mpuo.hooks)
}

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

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

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

// defaults sets the default values of the builder before save.
func (mpuo *ModelProviderUpdateOne) defaults() {
	if _, ok := mpuo.mutation.UpdatedAt(); !ok {
		v := modelprovider.UpdateDefaultUpdatedAt()
		mpuo.mutation.SetUpdatedAt(v)
	}
}

// check runs all checks and user-defined validators on the builder.
func (mpuo *ModelProviderUpdateOne) check() error {
	if v, ok := mpuo.mutation.Name(); ok {
		if err := modelprovider.NameValidator(v); err != nil {
			return &ValidationError{Name: "name", err: fmt.Errorf(`db: validator failed for field "ModelProvider.name": %w`, err)}
		}
	}
	if v, ok := mpuo.mutation.APIBase(); ok {
		if err := modelprovider.APIBaseValidator(v); err != nil {
			return &ValidationError{Name: "api_base", err: fmt.Errorf(`db: validator failed for field "ModelProvider.api_base": %w`, err)}
		}
	}
	return nil
}

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

func (mpuo *ModelProviderUpdateOne) sqlSave(ctx context.Context) (_node *ModelProvider, err error) {
	if err := mpuo.check(); err != nil {
		return _node, err
	}
	_spec := sqlgraph.NewUpdateSpec(modelprovider.Table, modelprovider.Columns, sqlgraph.NewFieldSpec(modelprovider.FieldID, field.TypeString))
	id, ok := mpuo.mutation.ID()
	if !ok {
		return nil, &ValidationError{Name: "id", err: errors.New(`db: missing "ModelProvider.id" for update`)}
	}
	_spec.Node.ID.Value = id
	if fields := mpuo.fields; len(fields) > 0 {
		_spec.Node.Columns = make([]string, 0, len(fields))
		_spec.Node.Columns = append(_spec.Node.Columns, modelprovider.FieldID)
		for _, f := range fields {
			if !modelprovider.ValidColumn(f) {
				return nil, &ValidationError{Name: f, err: fmt.Errorf("db: invalid field %q for query", f)}
			}
			if f != modelprovider.FieldID {
				_spec.Node.Columns = append(_spec.Node.Columns, f)
			}
		}
	}
	if ps := mpuo.mutation.predicates; len(ps) > 0 {
		_spec.Predicate = func(selector *sql.Selector) {
			for i := range ps {
				ps[i](selector)
			}
		}
	}
	if value, ok := mpuo.mutation.Name(); ok {
		_spec.SetField(modelprovider.FieldName, field.TypeString, value)
	}
	if value, ok := mpuo.mutation.APIBase(); ok {
		_spec.SetField(modelprovider.FieldAPIBase, field.TypeString, value)
	}
	if value, ok := mpuo.mutation.Priority(); ok {
		_spec.SetField(modelprovider.FieldPriority, field.TypeInt, value)
	}
	if value, ok := mpuo.mutation.AddedPriority(); ok {
		_spec.AddField(modelprovider.FieldPriority, field.TypeInt, value)
	}
	if value, ok := mpuo.mutation.CreatedAt(); ok {
		_spec.SetField(modelprovider.FieldCreatedAt, field.TypeTime, value)
	}
	if value, ok := mpuo.mutation.UpdatedAt(); ok {
		_spec.SetField(modelprovider.FieldUpdatedAt, field.TypeTime, value)
	}
	if mpuo.mutation.ModelsCleared() {
		edge := &sqlgraph.EdgeSpec{
			Rel:     sqlgraph.O2M,
			Inverse: false,
			Table:   modelprovider.ModelsTable,
			Columns: []string{modelprovider.ModelsColumn},
			Bidi:    false,
			Target: &sqlgraph.EdgeTarget{
				IDSpec: sqlgraph.NewFieldSpec(modelprovidermodel.FieldID, field.TypeUUID),
			},
		}
		_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
	}
	if nodes := mpuo.mutation.RemovedModelsIDs(); len(nodes) > 0 && !mpuo.mutation.ModelsCleared() {
		edge := &sqlgraph.EdgeSpec{
			Rel:     sqlgraph.O2M,
			Inverse: false,
			Table:   modelprovider.ModelsTable,
			Columns: []string{modelprovider.ModelsColumn},
			Bidi:    false,
			Target: &sqlgraph.EdgeTarget{
				IDSpec: sqlgraph.NewFieldSpec(modelprovidermodel.FieldID, field.TypeUUID),
			},
		}
		for _, k := range nodes {
			edge.Target.Nodes = append(edge.Target.Nodes, k)
		}
		_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
	}
	if nodes := mpuo.mutation.ModelsIDs(); len(nodes) > 0 {
		edge := &sqlgraph.EdgeSpec{
			Rel:     sqlgraph.O2M,
			Inverse: false,
			Table:   modelprovider.ModelsTable,
			Columns: []string{modelprovider.ModelsColumn},
			Bidi:    false,
			Target: &sqlgraph.EdgeTarget{
				IDSpec: sqlgraph.NewFieldSpec(modelprovidermodel.FieldID, field.TypeUUID),
			},
		}
		for _, k := range nodes {
			edge.Target.Nodes = append(edge.Target.Nodes, k)
		}
		_spec.Edges.Add = append(_spec.Edges.Add, edge)
	}
	_spec.AddModifiers(mpuo.modifiers...)
	_node = &ModelProvider{config: mpuo.config}
	_spec.Assign = _node.assignValues
	_spec.ScanValues = _node.scanValues
	if err = sqlgraph.UpdateNode(ctx, mpuo.driver, _spec); err != nil {
		if _, ok := err.(*sqlgraph.NotFoundError); ok {
			err = &NotFoundError{modelprovider.Label}
		} else if sqlgraph.IsConstraintError(err) {
			err = &ConstraintError{msg: err.Error(), wrap: err}
		}
		return nil, err
	}
	mpuo.mutation.done = true
	return _node, nil
}
