// Code generated by ent, DO NOT EDIT.

package ent

import (
	"context"
	"demo/ent/course"
	"demo/ent/enrollment"
	"demo/ent/student"
	"errors"
	"fmt"

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

// EnrollmentCreate is the builder for creating a Enrollment entity.
type EnrollmentCreate struct {
	config
	mutation *EnrollmentMutation
	hooks    []Hook
}

// SetSemester sets the "semester" field.
func (ec *EnrollmentCreate) SetSemester(s string) *EnrollmentCreate {
	ec.mutation.SetSemester(s)
	return ec
}

// SetYear sets the "year" field.
func (ec *EnrollmentCreate) SetYear(i int) *EnrollmentCreate {
	ec.mutation.SetYear(i)
	return ec
}

// SetStudentID sets the "student" edge to the Student entity by ID.
func (ec *EnrollmentCreate) SetStudentID(id int) *EnrollmentCreate {
	ec.mutation.SetStudentID(id)
	return ec
}

// SetStudent sets the "student" edge to the Student entity.
func (ec *EnrollmentCreate) SetStudent(s *Student) *EnrollmentCreate {
	return ec.SetStudentID(s.ID)
}

// SetCourseID sets the "course" edge to the Course entity by ID.
func (ec *EnrollmentCreate) SetCourseID(id int) *EnrollmentCreate {
	ec.mutation.SetCourseID(id)
	return ec
}

// SetCourse sets the "course" edge to the Course entity.
func (ec *EnrollmentCreate) SetCourse(c *Course) *EnrollmentCreate {
	return ec.SetCourseID(c.ID)
}

// Mutation returns the EnrollmentMutation object of the builder.
func (ec *EnrollmentCreate) Mutation() *EnrollmentMutation {
	return ec.mutation
}

// Save creates the Enrollment in the database.
func (ec *EnrollmentCreate) Save(ctx context.Context) (*Enrollment, error) {
	return withHooks(ctx, ec.sqlSave, ec.mutation, ec.hooks)
}

// SaveX calls Save and panics if Save returns an error.
func (ec *EnrollmentCreate) SaveX(ctx context.Context) *Enrollment {
	v, err := ec.Save(ctx)
	if err != nil {
		panic(err)
	}
	return v
}

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

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

// check runs all checks and user-defined validators on the builder.
func (ec *EnrollmentCreate) check() error {
	if _, ok := ec.mutation.Semester(); !ok {
		return &ValidationError{Name: "semester", err: errors.New(`ent: missing required field "Enrollment.semester"`)}
	}
	if v, ok := ec.mutation.Semester(); ok {
		if err := enrollment.SemesterValidator(v); err != nil {
			return &ValidationError{Name: "semester", err: fmt.Errorf(`ent: validator failed for field "Enrollment.semester": %w`, err)}
		}
	}
	if _, ok := ec.mutation.Year(); !ok {
		return &ValidationError{Name: "year", err: errors.New(`ent: missing required field "Enrollment.year"`)}
	}
	if v, ok := ec.mutation.Year(); ok {
		if err := enrollment.YearValidator(v); err != nil {
			return &ValidationError{Name: "year", err: fmt.Errorf(`ent: validator failed for field "Enrollment.year": %w`, err)}
		}
	}
	if _, ok := ec.mutation.StudentID(); !ok {
		return &ValidationError{Name: "student", err: errors.New(`ent: missing required edge "Enrollment.student"`)}
	}
	if _, ok := ec.mutation.CourseID(); !ok {
		return &ValidationError{Name: "course", err: errors.New(`ent: missing required edge "Enrollment.course"`)}
	}
	return nil
}

func (ec *EnrollmentCreate) sqlSave(ctx context.Context) (*Enrollment, error) {
	if err := ec.check(); err != nil {
		return nil, err
	}
	_node, _spec := ec.createSpec()
	if err := sqlgraph.CreateNode(ctx, ec.driver, _spec); err != nil {
		if sqlgraph.IsConstraintError(err) {
			err = &ConstraintError{msg: err.Error(), wrap: err}
		}
		return nil, err
	}
	id := _spec.ID.Value.(int64)
	_node.ID = int(id)
	ec.mutation.id = &_node.ID
	ec.mutation.done = true
	return _node, nil
}

func (ec *EnrollmentCreate) createSpec() (*Enrollment, *sqlgraph.CreateSpec) {
	var (
		_node = &Enrollment{config: ec.config}
		_spec = sqlgraph.NewCreateSpec(enrollment.Table, sqlgraph.NewFieldSpec(enrollment.FieldID, field.TypeInt))
	)
	if value, ok := ec.mutation.Semester(); ok {
		_spec.SetField(enrollment.FieldSemester, field.TypeString, value)
		_node.Semester = value
	}
	if value, ok := ec.mutation.Year(); ok {
		_spec.SetField(enrollment.FieldYear, field.TypeInt, value)
		_node.Year = value
	}
	if nodes := ec.mutation.StudentIDs(); len(nodes) > 0 {
		edge := &sqlgraph.EdgeSpec{
			Rel:     sqlgraph.M2O,
			Inverse: true,
			Table:   enrollment.StudentTable,
			Columns: []string{enrollment.StudentColumn},
			Bidi:    false,
			Target: &sqlgraph.EdgeTarget{
				IDSpec: sqlgraph.NewFieldSpec(student.FieldID, field.TypeInt),
			},
		}
		for _, k := range nodes {
			edge.Target.Nodes = append(edge.Target.Nodes, k)
		}
		_node.student_enrollments = &nodes[0]
		_spec.Edges = append(_spec.Edges, edge)
	}
	if nodes := ec.mutation.CourseIDs(); len(nodes) > 0 {
		edge := &sqlgraph.EdgeSpec{
			Rel:     sqlgraph.M2O,
			Inverse: true,
			Table:   enrollment.CourseTable,
			Columns: []string{enrollment.CourseColumn},
			Bidi:    false,
			Target: &sqlgraph.EdgeTarget{
				IDSpec: sqlgraph.NewFieldSpec(course.FieldID, field.TypeInt),
			},
		}
		for _, k := range nodes {
			edge.Target.Nodes = append(edge.Target.Nodes, k)
		}
		_node.course_enrollments = &nodes[0]
		_spec.Edges = append(_spec.Edges, edge)
	}
	return _node, _spec
}

// EnrollmentCreateBulk is the builder for creating many Enrollment entities in bulk.
type EnrollmentCreateBulk struct {
	config
	err      error
	builders []*EnrollmentCreate
}

// Save creates the Enrollment entities in the database.
func (ecb *EnrollmentCreateBulk) Save(ctx context.Context) ([]*Enrollment, error) {
	if ecb.err != nil {
		return nil, ecb.err
	}
	specs := make([]*sqlgraph.CreateSpec, len(ecb.builders))
	nodes := make([]*Enrollment, len(ecb.builders))
	mutators := make([]Mutator, len(ecb.builders))
	for i := range ecb.builders {
		func(i int, root context.Context) {
			builder := ecb.builders[i]
			var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
				mutation, ok := m.(*EnrollmentMutation)
				if !ok {
					return nil, fmt.Errorf("unexpected mutation type %T", m)
				}
				if err := builder.check(); err != nil {
					return nil, err
				}
				builder.mutation = mutation
				var err error
				nodes[i], specs[i] = builder.createSpec()
				if i < len(mutators)-1 {
					_, err = mutators[i+1].Mutate(root, ecb.builders[i+1].mutation)
				} else {
					spec := &sqlgraph.BatchCreateSpec{Nodes: specs}
					// Invoke the actual operation on the latest mutation in the chain.
					if err = sqlgraph.BatchCreate(ctx, ecb.driver, spec); err != nil {
						if sqlgraph.IsConstraintError(err) {
							err = &ConstraintError{msg: err.Error(), wrap: err}
						}
					}
				}
				if err != nil {
					return nil, err
				}
				mutation.id = &nodes[i].ID
				if specs[i].ID.Value != nil {
					id := specs[i].ID.Value.(int64)
					nodes[i].ID = int(id)
				}
				mutation.done = true
				return nodes[i], nil
			})
			for i := len(builder.hooks) - 1; i >= 0; i-- {
				mut = builder.hooks[i](mut)
			}
			mutators[i] = mut
		}(i, ctx)
	}
	if len(mutators) > 0 {
		if _, err := mutators[0].Mutate(ctx, ecb.builders[0].mutation); err != nil {
			return nil, err
		}
	}
	return nodes, nil
}

// SaveX is like Save, but panics if an error occurs.
func (ecb *EnrollmentCreateBulk) SaveX(ctx context.Context) []*Enrollment {
	v, err := ecb.Save(ctx)
	if err != nil {
		panic(err)
	}
	return v
}

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

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