// Code generated by ent, DO NOT EDIT.

package ent

import (
	"context"
	"demo/ent/course"
	"demo/ent/department"
	"demo/ent/enrollment"
	"demo/ent/predicate"
	"errors"
	"fmt"

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

// CourseUpdate is the builder for updating Course entities.
type CourseUpdate struct {
	config
	hooks    []Hook
	mutation *CourseMutation
}

// Where appends a list predicates to the CourseUpdate builder.
func (cu *CourseUpdate) Where(ps ...predicate.Course) *CourseUpdate {
	cu.mutation.Where(ps...)
	return cu
}

// SetTitle sets the "title" field.
func (cu *CourseUpdate) SetTitle(s string) *CourseUpdate {
	cu.mutation.SetTitle(s)
	return cu
}

// SetNillableTitle sets the "title" field if the given value is not nil.
func (cu *CourseUpdate) SetNillableTitle(s *string) *CourseUpdate {
	if s != nil {
		cu.SetTitle(*s)
	}
	return cu
}

// SetDepartmentID sets the "department" edge to the Department entity by ID.
func (cu *CourseUpdate) SetDepartmentID(id int) *CourseUpdate {
	cu.mutation.SetDepartmentID(id)
	return cu
}

// SetDepartment sets the "department" edge to the Department entity.
func (cu *CourseUpdate) SetDepartment(d *Department) *CourseUpdate {
	return cu.SetDepartmentID(d.ID)
}

// AddEnrollmentIDs adds the "enrollments" edge to the Enrollment entity by IDs.
func (cu *CourseUpdate) AddEnrollmentIDs(ids ...int) *CourseUpdate {
	cu.mutation.AddEnrollmentIDs(ids...)
	return cu
}

// AddEnrollments adds the "enrollments" edges to the Enrollment entity.
func (cu *CourseUpdate) AddEnrollments(e ...*Enrollment) *CourseUpdate {
	ids := make([]int, len(e))
	for i := range e {
		ids[i] = e[i].ID
	}
	return cu.AddEnrollmentIDs(ids...)
}

// Mutation returns the CourseMutation object of the builder.
func (cu *CourseUpdate) Mutation() *CourseMutation {
	return cu.mutation
}

// ClearDepartment clears the "department" edge to the Department entity.
func (cu *CourseUpdate) ClearDepartment() *CourseUpdate {
	cu.mutation.ClearDepartment()
	return cu
}

// ClearEnrollments clears all "enrollments" edges to the Enrollment entity.
func (cu *CourseUpdate) ClearEnrollments() *CourseUpdate {
	cu.mutation.ClearEnrollments()
	return cu
}

// RemoveEnrollmentIDs removes the "enrollments" edge to Enrollment entities by IDs.
func (cu *CourseUpdate) RemoveEnrollmentIDs(ids ...int) *CourseUpdate {
	cu.mutation.RemoveEnrollmentIDs(ids...)
	return cu
}

// RemoveEnrollments removes "enrollments" edges to Enrollment entities.
func (cu *CourseUpdate) RemoveEnrollments(e ...*Enrollment) *CourseUpdate {
	ids := make([]int, len(e))
	for i := range e {
		ids[i] = e[i].ID
	}
	return cu.RemoveEnrollmentIDs(ids...)
}

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

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

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

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

// check runs all checks and user-defined validators on the builder.
func (cu *CourseUpdate) check() error {
	if v, ok := cu.mutation.Title(); ok {
		if err := course.TitleValidator(v); err != nil {
			return &ValidationError{Name: "title", err: fmt.Errorf(`ent: validator failed for field "Course.title": %w`, err)}
		}
	}
	if _, ok := cu.mutation.DepartmentID(); cu.mutation.DepartmentCleared() && !ok {
		return errors.New(`ent: clearing a required unique edge "Course.department"`)
	}
	return nil
}

func (cu *CourseUpdate) sqlSave(ctx context.Context) (n int, err error) {
	if err := cu.check(); err != nil {
		return n, err
	}
	_spec := sqlgraph.NewUpdateSpec(course.Table, course.Columns, sqlgraph.NewFieldSpec(course.FieldID, field.TypeInt))
	if ps := cu.mutation.predicates; len(ps) > 0 {
		_spec.Predicate = func(selector *sql.Selector) {
			for i := range ps {
				ps[i](selector)
			}
		}
	}
	if value, ok := cu.mutation.Title(); ok {
		_spec.SetField(course.FieldTitle, field.TypeString, value)
	}
	if cu.mutation.DepartmentCleared() {
		edge := &sqlgraph.EdgeSpec{
			Rel:     sqlgraph.M2O,
			Inverse: true,
			Table:   course.DepartmentTable,
			Columns: []string{course.DepartmentColumn},
			Bidi:    false,
			Target: &sqlgraph.EdgeTarget{
				IDSpec: sqlgraph.NewFieldSpec(department.FieldID, field.TypeInt),
			},
		}
		_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
	}
	if nodes := cu.mutation.DepartmentIDs(); len(nodes) > 0 {
		edge := &sqlgraph.EdgeSpec{
			Rel:     sqlgraph.M2O,
			Inverse: true,
			Table:   course.DepartmentTable,
			Columns: []string{course.DepartmentColumn},
			Bidi:    false,
			Target: &sqlgraph.EdgeTarget{
				IDSpec: sqlgraph.NewFieldSpec(department.FieldID, field.TypeInt),
			},
		}
		for _, k := range nodes {
			edge.Target.Nodes = append(edge.Target.Nodes, k)
		}
		_spec.Edges.Add = append(_spec.Edges.Add, edge)
	}
	if cu.mutation.EnrollmentsCleared() {
		edge := &sqlgraph.EdgeSpec{
			Rel:     sqlgraph.O2M,
			Inverse: false,
			Table:   course.EnrollmentsTable,
			Columns: []string{course.EnrollmentsColumn},
			Bidi:    false,
			Target: &sqlgraph.EdgeTarget{
				IDSpec: sqlgraph.NewFieldSpec(enrollment.FieldID, field.TypeInt),
			},
		}
		_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
	}
	if nodes := cu.mutation.RemovedEnrollmentsIDs(); len(nodes) > 0 && !cu.mutation.EnrollmentsCleared() {
		edge := &sqlgraph.EdgeSpec{
			Rel:     sqlgraph.O2M,
			Inverse: false,
			Table:   course.EnrollmentsTable,
			Columns: []string{course.EnrollmentsColumn},
			Bidi:    false,
			Target: &sqlgraph.EdgeTarget{
				IDSpec: sqlgraph.NewFieldSpec(enrollment.FieldID, field.TypeInt),
			},
		}
		for _, k := range nodes {
			edge.Target.Nodes = append(edge.Target.Nodes, k)
		}
		_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
	}
	if nodes := cu.mutation.EnrollmentsIDs(); len(nodes) > 0 {
		edge := &sqlgraph.EdgeSpec{
			Rel:     sqlgraph.O2M,
			Inverse: false,
			Table:   course.EnrollmentsTable,
			Columns: []string{course.EnrollmentsColumn},
			Bidi:    false,
			Target: &sqlgraph.EdgeTarget{
				IDSpec: sqlgraph.NewFieldSpec(enrollment.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, cu.driver, _spec); err != nil {
		if _, ok := err.(*sqlgraph.NotFoundError); ok {
			err = &NotFoundError{course.Label}
		} else if sqlgraph.IsConstraintError(err) {
			err = &ConstraintError{msg: err.Error(), wrap: err}
		}
		return 0, err
	}
	cu.mutation.done = true
	return n, nil
}

// CourseUpdateOne is the builder for updating a single Course entity.
type CourseUpdateOne struct {
	config
	fields   []string
	hooks    []Hook
	mutation *CourseMutation
}

// SetTitle sets the "title" field.
func (cuo *CourseUpdateOne) SetTitle(s string) *CourseUpdateOne {
	cuo.mutation.SetTitle(s)
	return cuo
}

// SetNillableTitle sets the "title" field if the given value is not nil.
func (cuo *CourseUpdateOne) SetNillableTitle(s *string) *CourseUpdateOne {
	if s != nil {
		cuo.SetTitle(*s)
	}
	return cuo
}

// SetDepartmentID sets the "department" edge to the Department entity by ID.
func (cuo *CourseUpdateOne) SetDepartmentID(id int) *CourseUpdateOne {
	cuo.mutation.SetDepartmentID(id)
	return cuo
}

// SetDepartment sets the "department" edge to the Department entity.
func (cuo *CourseUpdateOne) SetDepartment(d *Department) *CourseUpdateOne {
	return cuo.SetDepartmentID(d.ID)
}

// AddEnrollmentIDs adds the "enrollments" edge to the Enrollment entity by IDs.
func (cuo *CourseUpdateOne) AddEnrollmentIDs(ids ...int) *CourseUpdateOne {
	cuo.mutation.AddEnrollmentIDs(ids...)
	return cuo
}

// AddEnrollments adds the "enrollments" edges to the Enrollment entity.
func (cuo *CourseUpdateOne) AddEnrollments(e ...*Enrollment) *CourseUpdateOne {
	ids := make([]int, len(e))
	for i := range e {
		ids[i] = e[i].ID
	}
	return cuo.AddEnrollmentIDs(ids...)
}

// Mutation returns the CourseMutation object of the builder.
func (cuo *CourseUpdateOne) Mutation() *CourseMutation {
	return cuo.mutation
}

// ClearDepartment clears the "department" edge to the Department entity.
func (cuo *CourseUpdateOne) ClearDepartment() *CourseUpdateOne {
	cuo.mutation.ClearDepartment()
	return cuo
}

// ClearEnrollments clears all "enrollments" edges to the Enrollment entity.
func (cuo *CourseUpdateOne) ClearEnrollments() *CourseUpdateOne {
	cuo.mutation.ClearEnrollments()
	return cuo
}

// RemoveEnrollmentIDs removes the "enrollments" edge to Enrollment entities by IDs.
func (cuo *CourseUpdateOne) RemoveEnrollmentIDs(ids ...int) *CourseUpdateOne {
	cuo.mutation.RemoveEnrollmentIDs(ids...)
	return cuo
}

// RemoveEnrollments removes "enrollments" edges to Enrollment entities.
func (cuo *CourseUpdateOne) RemoveEnrollments(e ...*Enrollment) *CourseUpdateOne {
	ids := make([]int, len(e))
	for i := range e {
		ids[i] = e[i].ID
	}
	return cuo.RemoveEnrollmentIDs(ids...)
}

// Where appends a list predicates to the CourseUpdate builder.
func (cuo *CourseUpdateOne) Where(ps ...predicate.Course) *CourseUpdateOne {
	cuo.mutation.Where(ps...)
	return cuo
}

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

// Save executes the query and returns the updated Course entity.
func (cuo *CourseUpdateOne) Save(ctx context.Context) (*Course, error) {
	return withHooks(ctx, cuo.sqlSave, cuo.mutation, cuo.hooks)
}

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

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

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

// check runs all checks and user-defined validators on the builder.
func (cuo *CourseUpdateOne) check() error {
	if v, ok := cuo.mutation.Title(); ok {
		if err := course.TitleValidator(v); err != nil {
			return &ValidationError{Name: "title", err: fmt.Errorf(`ent: validator failed for field "Course.title": %w`, err)}
		}
	}
	if _, ok := cuo.mutation.DepartmentID(); cuo.mutation.DepartmentCleared() && !ok {
		return errors.New(`ent: clearing a required unique edge "Course.department"`)
	}
	return nil
}

func (cuo *CourseUpdateOne) sqlSave(ctx context.Context) (_node *Course, err error) {
	if err := cuo.check(); err != nil {
		return _node, err
	}
	_spec := sqlgraph.NewUpdateSpec(course.Table, course.Columns, sqlgraph.NewFieldSpec(course.FieldID, field.TypeInt))
	id, ok := cuo.mutation.ID()
	if !ok {
		return nil, &ValidationError{Name: "id", err: errors.New(`ent: missing "Course.id" for update`)}
	}
	_spec.Node.ID.Value = id
	if fields := cuo.fields; len(fields) > 0 {
		_spec.Node.Columns = make([]string, 0, len(fields))
		_spec.Node.Columns = append(_spec.Node.Columns, course.FieldID)
		for _, f := range fields {
			if !course.ValidColumn(f) {
				return nil, &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)}
			}
			if f != course.FieldID {
				_spec.Node.Columns = append(_spec.Node.Columns, f)
			}
		}
	}
	if ps := cuo.mutation.predicates; len(ps) > 0 {
		_spec.Predicate = func(selector *sql.Selector) {
			for i := range ps {
				ps[i](selector)
			}
		}
	}
	if value, ok := cuo.mutation.Title(); ok {
		_spec.SetField(course.FieldTitle, field.TypeString, value)
	}
	if cuo.mutation.DepartmentCleared() {
		edge := &sqlgraph.EdgeSpec{
			Rel:     sqlgraph.M2O,
			Inverse: true,
			Table:   course.DepartmentTable,
			Columns: []string{course.DepartmentColumn},
			Bidi:    false,
			Target: &sqlgraph.EdgeTarget{
				IDSpec: sqlgraph.NewFieldSpec(department.FieldID, field.TypeInt),
			},
		}
		_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
	}
	if nodes := cuo.mutation.DepartmentIDs(); len(nodes) > 0 {
		edge := &sqlgraph.EdgeSpec{
			Rel:     sqlgraph.M2O,
			Inverse: true,
			Table:   course.DepartmentTable,
			Columns: []string{course.DepartmentColumn},
			Bidi:    false,
			Target: &sqlgraph.EdgeTarget{
				IDSpec: sqlgraph.NewFieldSpec(department.FieldID, field.TypeInt),
			},
		}
		for _, k := range nodes {
			edge.Target.Nodes = append(edge.Target.Nodes, k)
		}
		_spec.Edges.Add = append(_spec.Edges.Add, edge)
	}
	if cuo.mutation.EnrollmentsCleared() {
		edge := &sqlgraph.EdgeSpec{
			Rel:     sqlgraph.O2M,
			Inverse: false,
			Table:   course.EnrollmentsTable,
			Columns: []string{course.EnrollmentsColumn},
			Bidi:    false,
			Target: &sqlgraph.EdgeTarget{
				IDSpec: sqlgraph.NewFieldSpec(enrollment.FieldID, field.TypeInt),
			},
		}
		_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
	}
	if nodes := cuo.mutation.RemovedEnrollmentsIDs(); len(nodes) > 0 && !cuo.mutation.EnrollmentsCleared() {
		edge := &sqlgraph.EdgeSpec{
			Rel:     sqlgraph.O2M,
			Inverse: false,
			Table:   course.EnrollmentsTable,
			Columns: []string{course.EnrollmentsColumn},
			Bidi:    false,
			Target: &sqlgraph.EdgeTarget{
				IDSpec: sqlgraph.NewFieldSpec(enrollment.FieldID, field.TypeInt),
			},
		}
		for _, k := range nodes {
			edge.Target.Nodes = append(edge.Target.Nodes, k)
		}
		_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
	}
	if nodes := cuo.mutation.EnrollmentsIDs(); len(nodes) > 0 {
		edge := &sqlgraph.EdgeSpec{
			Rel:     sqlgraph.O2M,
			Inverse: false,
			Table:   course.EnrollmentsTable,
			Columns: []string{course.EnrollmentsColumn},
			Bidi:    false,
			Target: &sqlgraph.EdgeTarget{
				IDSpec: sqlgraph.NewFieldSpec(enrollment.FieldID, field.TypeInt),
			},
		}
		for _, k := range nodes {
			edge.Target.Nodes = append(edge.Target.Nodes, k)
		}
		_spec.Edges.Add = append(_spec.Edges.Add, edge)
	}
	_node = &Course{config: cuo.config}
	_spec.Assign = _node.assignValues
	_spec.ScanValues = _node.scanValues
	if err = sqlgraph.UpdateNode(ctx, cuo.driver, _spec); err != nil {
		if _, ok := err.(*sqlgraph.NotFoundError); ok {
			err = &NotFoundError{course.Label}
		} else if sqlgraph.IsConstraintError(err) {
			err = &ConstraintError{msg: err.Error(), wrap: err}
		}
		return nil, err
	}
	cuo.mutation.done = true
	return _node, nil
}
