// Code generated by ent, DO NOT EDIT.

package ent

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

	"entgo.io/ent/dialect/sql/sqlgraph"
	"entgo.io/ent/schema/field"
	"gitea.maison43.duckdns.org/gilles/matosbox/internal/data/ent/emplacement"
	"gitea.maison43.duckdns.org/gilles/matosbox/internal/data/ent/lienobjetemplacement"
	"github.com/google/uuid"
)

// EmplacementCreate is the builder for creating a Emplacement entity.
type EmplacementCreate struct {
	config
	mutation *EmplacementMutation
	hooks    []Hook
}

// SetNom sets the "nom" field.
func (_c *EmplacementCreate) SetNom(v string) *EmplacementCreate {
	_c.mutation.SetNom(v)
	return _c
}

// SetParentID sets the "parent_id" field.
func (_c *EmplacementCreate) SetParentID(v uuid.UUID) *EmplacementCreate {
	_c.mutation.SetParentID(v)
	return _c
}

// SetNillableParentID sets the "parent_id" field if the given value is not nil.
func (_c *EmplacementCreate) SetNillableParentID(v *uuid.UUID) *EmplacementCreate {
	if v != nil {
		_c.SetParentID(*v)
	}
	return _c
}

// SetSlug sets the "slug" field.
func (_c *EmplacementCreate) SetSlug(v string) *EmplacementCreate {
	_c.mutation.SetSlug(v)
	return _c
}

// SetNillableSlug sets the "slug" field if the given value is not nil.
func (_c *EmplacementCreate) SetNillableSlug(v *string) *EmplacementCreate {
	if v != nil {
		_c.SetSlug(*v)
	}
	return _c
}

// SetPiece sets the "piece" field.
func (_c *EmplacementCreate) SetPiece(v string) *EmplacementCreate {
	_c.mutation.SetPiece(v)
	return _c
}

// SetNillablePiece sets the "piece" field if the given value is not nil.
func (_c *EmplacementCreate) SetNillablePiece(v *string) *EmplacementCreate {
	if v != nil {
		_c.SetPiece(*v)
	}
	return _c
}

// SetMeuble sets the "meuble" field.
func (_c *EmplacementCreate) SetMeuble(v string) *EmplacementCreate {
	_c.mutation.SetMeuble(v)
	return _c
}

// SetNillableMeuble sets the "meuble" field if the given value is not nil.
func (_c *EmplacementCreate) SetNillableMeuble(v *string) *EmplacementCreate {
	if v != nil {
		_c.SetMeuble(*v)
	}
	return _c
}

// SetNumeroBoite sets the "numero_boite" field.
func (_c *EmplacementCreate) SetNumeroBoite(v string) *EmplacementCreate {
	_c.mutation.SetNumeroBoite(v)
	return _c
}

// SetNillableNumeroBoite sets the "numero_boite" field if the given value is not nil.
func (_c *EmplacementCreate) SetNillableNumeroBoite(v *string) *EmplacementCreate {
	if v != nil {
		_c.SetNumeroBoite(*v)
	}
	return _c
}

// SetIcone sets the "icone" field.
func (_c *EmplacementCreate) SetIcone(v string) *EmplacementCreate {
	_c.mutation.SetIcone(v)
	return _c
}

// SetNillableIcone sets the "icone" field if the given value is not nil.
func (_c *EmplacementCreate) SetNillableIcone(v *string) *EmplacementCreate {
	if v != nil {
		_c.SetIcone(*v)
	}
	return _c
}

// SetCreatedAt sets the "created_at" field.
func (_c *EmplacementCreate) SetCreatedAt(v time.Time) *EmplacementCreate {
	_c.mutation.SetCreatedAt(v)
	return _c
}

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

// SetUpdatedAt sets the "updated_at" field.
func (_c *EmplacementCreate) SetUpdatedAt(v time.Time) *EmplacementCreate {
	_c.mutation.SetUpdatedAt(v)
	return _c
}

// SetNillableUpdatedAt sets the "updated_at" field if the given value is not nil.
func (_c *EmplacementCreate) SetNillableUpdatedAt(v *time.Time) *EmplacementCreate {
	if v != nil {
		_c.SetUpdatedAt(*v)
	}
	return _c
}

// SetID sets the "id" field.
func (_c *EmplacementCreate) SetID(v uuid.UUID) *EmplacementCreate {
	_c.mutation.SetID(v)
	return _c
}

// SetNillableID sets the "id" field if the given value is not nil.
func (_c *EmplacementCreate) SetNillableID(v *uuid.UUID) *EmplacementCreate {
	if v != nil {
		_c.SetID(*v)
	}
	return _c
}

// SetParent sets the "parent" edge to the Emplacement entity.
func (_c *EmplacementCreate) SetParent(v *Emplacement) *EmplacementCreate {
	return _c.SetParentID(v.ID)
}

// AddEnfantIDs adds the "enfants" edge to the Emplacement entity by IDs.
func (_c *EmplacementCreate) AddEnfantIDs(ids ...uuid.UUID) *EmplacementCreate {
	_c.mutation.AddEnfantIDs(ids...)
	return _c
}

// AddEnfants adds the "enfants" edges to the Emplacement entity.
func (_c *EmplacementCreate) AddEnfants(v ...*Emplacement) *EmplacementCreate {
	ids := make([]uuid.UUID, len(v))
	for i := range v {
		ids[i] = v[i].ID
	}
	return _c.AddEnfantIDs(ids...)
}

// AddLiensObjetIDs adds the "liens_objets" edge to the LienObjetEmplacement entity by IDs.
func (_c *EmplacementCreate) AddLiensObjetIDs(ids ...uuid.UUID) *EmplacementCreate {
	_c.mutation.AddLiensObjetIDs(ids...)
	return _c
}

// AddLiensObjets adds the "liens_objets" edges to the LienObjetEmplacement entity.
func (_c *EmplacementCreate) AddLiensObjets(v ...*LienObjetEmplacement) *EmplacementCreate {
	ids := make([]uuid.UUID, len(v))
	for i := range v {
		ids[i] = v[i].ID
	}
	return _c.AddLiensObjetIDs(ids...)
}

// Mutation returns the EmplacementMutation object of the builder.
func (_c *EmplacementCreate) Mutation() *EmplacementMutation {
	return _c.mutation
}

// Save creates the Emplacement in the database.
func (_c *EmplacementCreate) Save(ctx context.Context) (*Emplacement, error) {
	_c.defaults()
	return withHooks(ctx, _c.sqlSave, _c.mutation, _c.hooks)
}

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

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

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

// defaults sets the default values of the builder before save.
func (_c *EmplacementCreate) defaults() {
	if _, ok := _c.mutation.CreatedAt(); !ok {
		v := emplacement.DefaultCreatedAt()
		_c.mutation.SetCreatedAt(v)
	}
	if _, ok := _c.mutation.UpdatedAt(); !ok {
		v := emplacement.DefaultUpdatedAt()
		_c.mutation.SetUpdatedAt(v)
	}
	if _, ok := _c.mutation.ID(); !ok {
		v := emplacement.DefaultID()
		_c.mutation.SetID(v)
	}
}

// check runs all checks and user-defined validators on the builder.
func (_c *EmplacementCreate) check() error {
	if _, ok := _c.mutation.Nom(); !ok {
		return &ValidationError{Name: "nom", err: errors.New(`ent: missing required field "Emplacement.nom"`)}
	}
	if v, ok := _c.mutation.Nom(); ok {
		if err := emplacement.NomValidator(v); err != nil {
			return &ValidationError{Name: "nom", err: fmt.Errorf(`ent: validator failed for field "Emplacement.nom": %w`, err)}
		}
	}
	if _, ok := _c.mutation.CreatedAt(); !ok {
		return &ValidationError{Name: "created_at", err: errors.New(`ent: missing required field "Emplacement.created_at"`)}
	}
	if _, ok := _c.mutation.UpdatedAt(); !ok {
		return &ValidationError{Name: "updated_at", err: errors.New(`ent: missing required field "Emplacement.updated_at"`)}
	}
	return nil
}

func (_c *EmplacementCreate) sqlSave(ctx context.Context) (*Emplacement, error) {
	if err := _c.check(); err != nil {
		return nil, err
	}
	_node, _spec := _c.createSpec()
	if err := sqlgraph.CreateNode(ctx, _c.driver, _spec); err != nil {
		if sqlgraph.IsConstraintError(err) {
			err = &ConstraintError{msg: err.Error(), wrap: err}
		}
		return nil, err
	}
	if _spec.ID.Value != nil {
		if id, ok := _spec.ID.Value.(*uuid.UUID); ok {
			_node.ID = *id
		} else if err := _node.ID.Scan(_spec.ID.Value); err != nil {
			return nil, err
		}
	}
	_c.mutation.id = &_node.ID
	_c.mutation.done = true
	return _node, nil
}

func (_c *EmplacementCreate) createSpec() (*Emplacement, *sqlgraph.CreateSpec) {
	var (
		_node = &Emplacement{config: _c.config}
		_spec = sqlgraph.NewCreateSpec(emplacement.Table, sqlgraph.NewFieldSpec(emplacement.FieldID, field.TypeUUID))
	)
	if id, ok := _c.mutation.ID(); ok {
		_node.ID = id
		_spec.ID.Value = &id
	}
	if value, ok := _c.mutation.Nom(); ok {
		_spec.SetField(emplacement.FieldNom, field.TypeString, value)
		_node.Nom = value
	}
	if value, ok := _c.mutation.Slug(); ok {
		_spec.SetField(emplacement.FieldSlug, field.TypeString, value)
		_node.Slug = &value
	}
	if value, ok := _c.mutation.Piece(); ok {
		_spec.SetField(emplacement.FieldPiece, field.TypeString, value)
		_node.Piece = &value
	}
	if value, ok := _c.mutation.Meuble(); ok {
		_spec.SetField(emplacement.FieldMeuble, field.TypeString, value)
		_node.Meuble = &value
	}
	if value, ok := _c.mutation.NumeroBoite(); ok {
		_spec.SetField(emplacement.FieldNumeroBoite, field.TypeString, value)
		_node.NumeroBoite = &value
	}
	if value, ok := _c.mutation.Icone(); ok {
		_spec.SetField(emplacement.FieldIcone, field.TypeString, value)
		_node.Icone = &value
	}
	if value, ok := _c.mutation.CreatedAt(); ok {
		_spec.SetField(emplacement.FieldCreatedAt, field.TypeTime, value)
		_node.CreatedAt = value
	}
	if value, ok := _c.mutation.UpdatedAt(); ok {
		_spec.SetField(emplacement.FieldUpdatedAt, field.TypeTime, value)
		_node.UpdatedAt = value
	}
	if nodes := _c.mutation.ParentIDs(); len(nodes) > 0 {
		edge := &sqlgraph.EdgeSpec{
			Rel:     sqlgraph.M2O,
			Inverse: true,
			Table:   emplacement.ParentTable,
			Columns: []string{emplacement.ParentColumn},
			Bidi:    false,
			Target: &sqlgraph.EdgeTarget{
				IDSpec: sqlgraph.NewFieldSpec(emplacement.FieldID, field.TypeUUID),
			},
		}
		for _, k := range nodes {
			edge.Target.Nodes = append(edge.Target.Nodes, k)
		}
		_node.ParentID = &nodes[0]
		_spec.Edges = append(_spec.Edges, edge)
	}
	if nodes := _c.mutation.EnfantsIDs(); len(nodes) > 0 {
		edge := &sqlgraph.EdgeSpec{
			Rel:     sqlgraph.O2M,
			Inverse: false,
			Table:   emplacement.EnfantsTable,
			Columns: []string{emplacement.EnfantsColumn},
			Bidi:    false,
			Target: &sqlgraph.EdgeTarget{
				IDSpec: sqlgraph.NewFieldSpec(emplacement.FieldID, field.TypeUUID),
			},
		}
		for _, k := range nodes {
			edge.Target.Nodes = append(edge.Target.Nodes, k)
		}
		_spec.Edges = append(_spec.Edges, edge)
	}
	if nodes := _c.mutation.LiensObjetsIDs(); len(nodes) > 0 {
		edge := &sqlgraph.EdgeSpec{
			Rel:     sqlgraph.O2M,
			Inverse: false,
			Table:   emplacement.LiensObjetsTable,
			Columns: []string{emplacement.LiensObjetsColumn},
			Bidi:    false,
			Target: &sqlgraph.EdgeTarget{
				IDSpec: sqlgraph.NewFieldSpec(lienobjetemplacement.FieldID, field.TypeUUID),
			},
		}
		for _, k := range nodes {
			edge.Target.Nodes = append(edge.Target.Nodes, k)
		}
		_spec.Edges = append(_spec.Edges, edge)
	}
	return _node, _spec
}

// EmplacementCreateBulk is the builder for creating many Emplacement entities in bulk.
type EmplacementCreateBulk struct {
	config
	err      error
	builders []*EmplacementCreate
}

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

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

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

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