// Code generated by entc, DO NOT EDIT.

package ent

import (
	"context"
	"errors"
	"fmt"

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

	"github.com/pingcap/test-infra/common/model"
	"github.com/pingcap/test-infra/services/tcms/service/store/v2/ent/internal"
	"github.com/pingcap/test-infra/services/tcms/service/store/v2/ent/predicate"
	"github.com/pingcap/test-infra/services/tcms/service/store/v2/ent/resourceduration"
)

// ResourceDurationUpdate is the builder for updating ResourceDuration entities.
type ResourceDurationUpdate struct {
	config
	hooks    []Hook
	mutation *ResourceDurationMutation
}

// Where appends a list predicates to the ResourceDurationUpdate builder.
func (rdu *ResourceDurationUpdate) Where(ps ...predicate.ResourceDuration) *ResourceDurationUpdate {
	rdu.mutation.Where(ps...)
	return rdu
}

// SetPlanExecutionID sets the "planExecutionID" field.
func (rdu *ResourceDurationUpdate) SetPlanExecutionID(m model.ID) *ResourceDurationUpdate {
	rdu.mutation.ResetPlanExecutionID()
	rdu.mutation.SetPlanExecutionID(m)
	return rdu
}

// AddPlanExecutionID adds m to the "planExecutionID" field.
func (rdu *ResourceDurationUpdate) AddPlanExecutionID(m model.ID) *ResourceDurationUpdate {
	rdu.mutation.AddPlanExecutionID(m)
	return rdu
}

// SetType sets the "type" field.
func (rdu *ResourceDurationUpdate) SetType(mdt model.ResourceDurationType) *ResourceDurationUpdate {
	rdu.mutation.SetType(mdt)
	return rdu
}

// SetNillableType sets the "type" field if the given value is not nil.
func (rdu *ResourceDurationUpdate) SetNillableType(mdt *model.ResourceDurationType) *ResourceDurationUpdate {
	if mdt != nil {
		rdu.SetType(*mdt)
	}
	return rdu
}

// SetCpuDuration sets the "cpuDuration" field.
func (rdu *ResourceDurationUpdate) SetCpuDuration(u uint64) *ResourceDurationUpdate {
	rdu.mutation.ResetCpuDuration()
	rdu.mutation.SetCpuDuration(u)
	return rdu
}

// AddCpuDuration adds u to the "cpuDuration" field.
func (rdu *ResourceDurationUpdate) AddCpuDuration(u int64) *ResourceDurationUpdate {
	rdu.mutation.AddCpuDuration(u)
	return rdu
}

// SetMemoryDuration sets the "memoryDuration" field.
func (rdu *ResourceDurationUpdate) SetMemoryDuration(u uint64) *ResourceDurationUpdate {
	rdu.mutation.ResetMemoryDuration()
	rdu.mutation.SetMemoryDuration(u)
	return rdu
}

// AddMemoryDuration adds u to the "memoryDuration" field.
func (rdu *ResourceDurationUpdate) AddMemoryDuration(u int64) *ResourceDurationUpdate {
	rdu.mutation.AddMemoryDuration(u)
	return rdu
}

// Mutation returns the ResourceDurationMutation object of the builder.
func (rdu *ResourceDurationUpdate) Mutation() *ResourceDurationMutation {
	return rdu.mutation
}

// Save executes the query and returns the number of nodes affected by the update operation.
func (rdu *ResourceDurationUpdate) Save(ctx context.Context) (int, error) {
	var (
		err      error
		affected int
	)
	rdu.defaults()
	if len(rdu.hooks) == 0 {
		if err = rdu.check(); err != nil {
			return 0, err
		}
		affected, err = rdu.sqlSave(ctx)
	} else {
		var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
			mutation, ok := m.(*ResourceDurationMutation)
			if !ok {
				return nil, fmt.Errorf("unexpected mutation type %T", m)
			}
			if err = rdu.check(); err != nil {
				return 0, err
			}
			rdu.mutation = mutation
			affected, err = rdu.sqlSave(ctx)
			mutation.done = true
			return affected, err
		})
		for i := len(rdu.hooks) - 1; i >= 0; i-- {
			if rdu.hooks[i] == nil {
				return 0, fmt.Errorf("ent: uninitialized hook (forgotten import ent/runtime?)")
			}
			mut = rdu.hooks[i](mut)
		}
		if _, err := mut.Mutate(ctx, rdu.mutation); err != nil {
			return 0, err
		}
	}
	return affected, err
}

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

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

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

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

// check runs all checks and user-defined validators on the builder.
func (rdu *ResourceDurationUpdate) check() error {
	if v, ok := rdu.mutation.PlanExecutionID(); ok {
		if err := resourceduration.PlanExecutionIDValidator(uint64(v)); err != nil {
			return &ValidationError{Name: "planExecutionID", err: fmt.Errorf(`ent: validator failed for field "ResourceDuration.planExecutionID": %w`, err)}
		}
	}
	if v, ok := rdu.mutation.GetType(); ok {
		if err := resourceduration.TypeValidator(v); err != nil {
			return &ValidationError{Name: "type", err: fmt.Errorf(`ent: validator failed for field "ResourceDuration.type": %w`, err)}
		}
	}
	return nil
}

func (rdu *ResourceDurationUpdate) sqlSave(ctx context.Context) (n int, err error) {
	_spec := &sqlgraph.UpdateSpec{
		Node: &sqlgraph.NodeSpec{
			Table:   resourceduration.Table,
			Columns: resourceduration.Columns,
			ID: &sqlgraph.FieldSpec{
				Type:   field.TypeUint64,
				Column: resourceduration.FieldID,
			},
		},
	}
	if ps := rdu.mutation.predicates; len(ps) > 0 {
		_spec.Predicate = func(selector *sql.Selector) {
			for i := range ps {
				ps[i](selector)
			}
		}
	}
	if value, ok := rdu.mutation.UpdatedAt(); ok {
		_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
			Type:   field.TypeTime,
			Value:  value,
			Column: resourceduration.FieldUpdatedAt,
		})
	}
	if value, ok := rdu.mutation.PlanExecutionID(); ok {
		_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
			Type:   field.TypeUint64,
			Value:  value,
			Column: resourceduration.FieldPlanExecutionID,
		})
	}
	if value, ok := rdu.mutation.AddedPlanExecutionID(); ok {
		_spec.Fields.Add = append(_spec.Fields.Add, &sqlgraph.FieldSpec{
			Type:   field.TypeUint64,
			Value:  value,
			Column: resourceduration.FieldPlanExecutionID,
		})
	}
	if value, ok := rdu.mutation.GetType(); ok {
		_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
			Type:   field.TypeEnum,
			Value:  value,
			Column: resourceduration.FieldType,
		})
	}
	if value, ok := rdu.mutation.CpuDuration(); ok {
		_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
			Type:   field.TypeUint64,
			Value:  value,
			Column: resourceduration.FieldCpuDuration,
		})
	}
	if value, ok := rdu.mutation.AddedCpuDuration(); ok {
		_spec.Fields.Add = append(_spec.Fields.Add, &sqlgraph.FieldSpec{
			Type:   field.TypeUint64,
			Value:  value,
			Column: resourceduration.FieldCpuDuration,
		})
	}
	if value, ok := rdu.mutation.MemoryDuration(); ok {
		_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
			Type:   field.TypeUint64,
			Value:  value,
			Column: resourceduration.FieldMemoryDuration,
		})
	}
	if value, ok := rdu.mutation.AddedMemoryDuration(); ok {
		_spec.Fields.Add = append(_spec.Fields.Add, &sqlgraph.FieldSpec{
			Type:   field.TypeUint64,
			Value:  value,
			Column: resourceduration.FieldMemoryDuration,
		})
	}
	_spec.Node.Schema = rdu.schemaConfig.ResourceDuration
	ctx = internal.NewSchemaConfigContext(ctx, rdu.schemaConfig)
	if n, err = sqlgraph.UpdateNodes(ctx, rdu.driver, _spec); err != nil {
		if _, ok := err.(*sqlgraph.NotFoundError); ok {
			err = &NotFoundError{resourceduration.Label}
		} else if sqlgraph.IsConstraintError(err) {
			err = &ConstraintError{err.Error(), err}
		}
		return 0, err
	}
	return n, nil
}

// ResourceDurationUpdateOne is the builder for updating a single ResourceDuration entity.
type ResourceDurationUpdateOne struct {
	config
	fields   []string
	hooks    []Hook
	mutation *ResourceDurationMutation
}

// SetPlanExecutionID sets the "planExecutionID" field.
func (rduo *ResourceDurationUpdateOne) SetPlanExecutionID(m model.ID) *ResourceDurationUpdateOne {
	rduo.mutation.ResetPlanExecutionID()
	rduo.mutation.SetPlanExecutionID(m)
	return rduo
}

// AddPlanExecutionID adds m to the "planExecutionID" field.
func (rduo *ResourceDurationUpdateOne) AddPlanExecutionID(m model.ID) *ResourceDurationUpdateOne {
	rduo.mutation.AddPlanExecutionID(m)
	return rduo
}

// SetType sets the "type" field.
func (rduo *ResourceDurationUpdateOne) SetType(mdt model.ResourceDurationType) *ResourceDurationUpdateOne {
	rduo.mutation.SetType(mdt)
	return rduo
}

// SetNillableType sets the "type" field if the given value is not nil.
func (rduo *ResourceDurationUpdateOne) SetNillableType(mdt *model.ResourceDurationType) *ResourceDurationUpdateOne {
	if mdt != nil {
		rduo.SetType(*mdt)
	}
	return rduo
}

// SetCpuDuration sets the "cpuDuration" field.
func (rduo *ResourceDurationUpdateOne) SetCpuDuration(u uint64) *ResourceDurationUpdateOne {
	rduo.mutation.ResetCpuDuration()
	rduo.mutation.SetCpuDuration(u)
	return rduo
}

// AddCpuDuration adds u to the "cpuDuration" field.
func (rduo *ResourceDurationUpdateOne) AddCpuDuration(u int64) *ResourceDurationUpdateOne {
	rduo.mutation.AddCpuDuration(u)
	return rduo
}

// SetMemoryDuration sets the "memoryDuration" field.
func (rduo *ResourceDurationUpdateOne) SetMemoryDuration(u uint64) *ResourceDurationUpdateOne {
	rduo.mutation.ResetMemoryDuration()
	rduo.mutation.SetMemoryDuration(u)
	return rduo
}

// AddMemoryDuration adds u to the "memoryDuration" field.
func (rduo *ResourceDurationUpdateOne) AddMemoryDuration(u int64) *ResourceDurationUpdateOne {
	rduo.mutation.AddMemoryDuration(u)
	return rduo
}

// Mutation returns the ResourceDurationMutation object of the builder.
func (rduo *ResourceDurationUpdateOne) Mutation() *ResourceDurationMutation {
	return rduo.mutation
}

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

// Save executes the query and returns the updated ResourceDuration entity.
func (rduo *ResourceDurationUpdateOne) Save(ctx context.Context) (*ResourceDuration, error) {
	var (
		err  error
		node *ResourceDuration
	)
	rduo.defaults()
	if len(rduo.hooks) == 0 {
		if err = rduo.check(); err != nil {
			return nil, err
		}
		node, err = rduo.sqlSave(ctx)
	} else {
		var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
			mutation, ok := m.(*ResourceDurationMutation)
			if !ok {
				return nil, fmt.Errorf("unexpected mutation type %T", m)
			}
			if err = rduo.check(); err != nil {
				return nil, err
			}
			rduo.mutation = mutation
			node, err = rduo.sqlSave(ctx)
			mutation.done = true
			return node, err
		})
		for i := len(rduo.hooks) - 1; i >= 0; i-- {
			if rduo.hooks[i] == nil {
				return nil, fmt.Errorf("ent: uninitialized hook (forgotten import ent/runtime?)")
			}
			mut = rduo.hooks[i](mut)
		}
		if _, err := mut.Mutate(ctx, rduo.mutation); err != nil {
			return nil, err
		}
	}
	return node, err
}

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

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

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

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

// check runs all checks and user-defined validators on the builder.
func (rduo *ResourceDurationUpdateOne) check() error {
	if v, ok := rduo.mutation.PlanExecutionID(); ok {
		if err := resourceduration.PlanExecutionIDValidator(uint64(v)); err != nil {
			return &ValidationError{Name: "planExecutionID", err: fmt.Errorf(`ent: validator failed for field "ResourceDuration.planExecutionID": %w`, err)}
		}
	}
	if v, ok := rduo.mutation.GetType(); ok {
		if err := resourceduration.TypeValidator(v); err != nil {
			return &ValidationError{Name: "type", err: fmt.Errorf(`ent: validator failed for field "ResourceDuration.type": %w`, err)}
		}
	}
	return nil
}

func (rduo *ResourceDurationUpdateOne) sqlSave(ctx context.Context) (_node *ResourceDuration, err error) {
	_spec := &sqlgraph.UpdateSpec{
		Node: &sqlgraph.NodeSpec{
			Table:   resourceduration.Table,
			Columns: resourceduration.Columns,
			ID: &sqlgraph.FieldSpec{
				Type:   field.TypeUint64,
				Column: resourceduration.FieldID,
			},
		},
	}
	id, ok := rduo.mutation.ID()
	if !ok {
		return nil, &ValidationError{Name: "id", err: errors.New(`ent: missing "ResourceDuration.id" for update`)}
	}
	_spec.Node.ID.Value = id
	if fields := rduo.fields; len(fields) > 0 {
		_spec.Node.Columns = make([]string, 0, len(fields))
		_spec.Node.Columns = append(_spec.Node.Columns, resourceduration.FieldID)
		for _, f := range fields {
			if !resourceduration.ValidColumn(f) {
				return nil, &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)}
			}
			if f != resourceduration.FieldID {
				_spec.Node.Columns = append(_spec.Node.Columns, f)
			}
		}
	}
	if ps := rduo.mutation.predicates; len(ps) > 0 {
		_spec.Predicate = func(selector *sql.Selector) {
			for i := range ps {
				ps[i](selector)
			}
		}
	}
	if value, ok := rduo.mutation.UpdatedAt(); ok {
		_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
			Type:   field.TypeTime,
			Value:  value,
			Column: resourceduration.FieldUpdatedAt,
		})
	}
	if value, ok := rduo.mutation.PlanExecutionID(); ok {
		_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
			Type:   field.TypeUint64,
			Value:  value,
			Column: resourceduration.FieldPlanExecutionID,
		})
	}
	if value, ok := rduo.mutation.AddedPlanExecutionID(); ok {
		_spec.Fields.Add = append(_spec.Fields.Add, &sqlgraph.FieldSpec{
			Type:   field.TypeUint64,
			Value:  value,
			Column: resourceduration.FieldPlanExecutionID,
		})
	}
	if value, ok := rduo.mutation.GetType(); ok {
		_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
			Type:   field.TypeEnum,
			Value:  value,
			Column: resourceduration.FieldType,
		})
	}
	if value, ok := rduo.mutation.CpuDuration(); ok {
		_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
			Type:   field.TypeUint64,
			Value:  value,
			Column: resourceduration.FieldCpuDuration,
		})
	}
	if value, ok := rduo.mutation.AddedCpuDuration(); ok {
		_spec.Fields.Add = append(_spec.Fields.Add, &sqlgraph.FieldSpec{
			Type:   field.TypeUint64,
			Value:  value,
			Column: resourceduration.FieldCpuDuration,
		})
	}
	if value, ok := rduo.mutation.MemoryDuration(); ok {
		_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
			Type:   field.TypeUint64,
			Value:  value,
			Column: resourceduration.FieldMemoryDuration,
		})
	}
	if value, ok := rduo.mutation.AddedMemoryDuration(); ok {
		_spec.Fields.Add = append(_spec.Fields.Add, &sqlgraph.FieldSpec{
			Type:   field.TypeUint64,
			Value:  value,
			Column: resourceduration.FieldMemoryDuration,
		})
	}
	_spec.Node.Schema = rduo.schemaConfig.ResourceDuration
	ctx = internal.NewSchemaConfigContext(ctx, rduo.schemaConfig)
	_node = &ResourceDuration{config: rduo.config}
	_spec.Assign = _node.assignValues
	_spec.ScanValues = _node.scanValues
	if err = sqlgraph.UpdateNode(ctx, rduo.driver, _spec); err != nil {
		if _, ok := err.(*sqlgraph.NotFoundError); ok {
			err = &NotFoundError{resourceduration.Label}
		} else if sqlgraph.IsConstraintError(err) {
			err = &ConstraintError{err.Error(), err}
		}
		return nil, err
	}
	return _node, nil
}
