// Code generated by ent, DO NOT EDIT.

package ent

import (
	"context"
	"demo/ent/department"
	"demo/ent/instructor"
	"errors"
	"fmt"

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

// InstructorCreate is the builder for creating a Instructor entity.
type InstructorCreate struct {
	config
	mutation *InstructorMutation
	hooks    []Hook
}

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

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

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

// Mutation returns the InstructorMutation object of the builder.
func (ic *InstructorCreate) Mutation() *InstructorMutation {
	return ic.mutation
}

// Save creates the Instructor in the database.
func (ic *InstructorCreate) Save(ctx context.Context) (*Instructor, error) {
	return withHooks(ctx, ic.sqlSave, ic.mutation, ic.hooks)
}

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

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

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

// check runs all checks and user-defined validators on the builder.
func (ic *InstructorCreate) check() error {
	if _, ok := ic.mutation.Name(); !ok {
		return &ValidationError{Name: "name", err: errors.New(`ent: missing required field "Instructor.name"`)}
	}
	if v, ok := ic.mutation.Name(); ok {
		if err := instructor.NameValidator(v); err != nil {
			return &ValidationError{Name: "name", err: fmt.Errorf(`ent: validator failed for field "Instructor.name": %w`, err)}
		}
	}
	if _, ok := ic.mutation.DepartmentID(); !ok {
		return &ValidationError{Name: "department", err: errors.New(`ent: missing required edge "Instructor.department"`)}
	}
	return nil
}

func (ic *InstructorCreate) sqlSave(ctx context.Context) (*Instructor, error) {
	if err := ic.check(); err != nil {
		return nil, err
	}
	_node, _spec := ic.createSpec()
	if err := sqlgraph.CreateNode(ctx, ic.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)
	ic.mutation.id = &_node.ID
	ic.mutation.done = true
	return _node, nil
}

func (ic *InstructorCreate) createSpec() (*Instructor, *sqlgraph.CreateSpec) {
	var (
		_node = &Instructor{config: ic.config}
		_spec = sqlgraph.NewCreateSpec(instructor.Table, sqlgraph.NewFieldSpec(instructor.FieldID, field.TypeInt))
	)
	if value, ok := ic.mutation.Name(); ok {
		_spec.SetField(instructor.FieldName, field.TypeString, value)
		_node.Name = value
	}
	if nodes := ic.mutation.DepartmentIDs(); len(nodes) > 0 {
		edge := &sqlgraph.EdgeSpec{
			Rel:     sqlgraph.M2O,
			Inverse: true,
			Table:   instructor.DepartmentTable,
			Columns: []string{instructor.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)
		}
		_node.department_instructors = &nodes[0]
		_spec.Edges = append(_spec.Edges, edge)
	}
	return _node, _spec
}

// InstructorCreateBulk is the builder for creating many Instructor entities in bulk.
type InstructorCreateBulk struct {
	config
	err      error
	builders []*InstructorCreate
}

// Save creates the Instructor entities in the database.
func (icb *InstructorCreateBulk) Save(ctx context.Context) ([]*Instructor, error) {
	if icb.err != nil {
		return nil, icb.err
	}
	specs := make([]*sqlgraph.CreateSpec, len(icb.builders))
	nodes := make([]*Instructor, len(icb.builders))
	mutators := make([]Mutator, len(icb.builders))
	for i := range icb.builders {
		func(i int, root context.Context) {
			builder := icb.builders[i]
			var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
				mutation, ok := m.(*InstructorMutation)
				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, icb.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, icb.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, icb.builders[0].mutation); err != nil {
			return nil, err
		}
	}
	return nodes, nil
}

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

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

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