// 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/categorie"
	"github.com/google/uuid"
)

// CategorieCreate is the builder for creating a Categorie entity.
type CategorieCreate struct {
	config
	mutation *CategorieMutation
	hooks    []Hook
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

// ExecX is like Exec, but panics if an error occurs.
func (_c *CategorieCreate) 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 *CategorieCreate) defaults() {
	if _, ok := _c.mutation.CreatedAt(); !ok {
		v := categorie.DefaultCreatedAt()
		_c.mutation.SetCreatedAt(v)
	}
	if _, ok := _c.mutation.UpdatedAt(); !ok {
		v := categorie.DefaultUpdatedAt()
		_c.mutation.SetUpdatedAt(v)
	}
	if _, ok := _c.mutation.ID(); !ok {
		v := categorie.DefaultID()
		_c.mutation.SetID(v)
	}
}

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

func (_c *CategorieCreate) sqlSave(ctx context.Context) (*Categorie, 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 *CategorieCreate) createSpec() (*Categorie, *sqlgraph.CreateSpec) {
	var (
		_node = &Categorie{config: _c.config}
		_spec = sqlgraph.NewCreateSpec(categorie.Table, sqlgraph.NewFieldSpec(categorie.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(categorie.FieldNom, field.TypeString, value)
		_node.Nom = value
	}
	if value, ok := _c.mutation.Slug(); ok {
		_spec.SetField(categorie.FieldSlug, field.TypeString, value)
		_node.Slug = &value
	}
	if value, ok := _c.mutation.Icone(); ok {
		_spec.SetField(categorie.FieldIcone, field.TypeString, value)
		_node.Icone = &value
	}
	if value, ok := _c.mutation.CreatedAt(); ok {
		_spec.SetField(categorie.FieldCreatedAt, field.TypeTime, value)
		_node.CreatedAt = value
	}
	if value, ok := _c.mutation.UpdatedAt(); ok {
		_spec.SetField(categorie.FieldUpdatedAt, field.TypeTime, value)
		_node.UpdatedAt = value
	}
	if nodes := _c.mutation.ParentIDs(); len(nodes) > 0 {
		edge := &sqlgraph.EdgeSpec{
			Rel:     sqlgraph.M2O,
			Inverse: true,
			Table:   categorie.ParentTable,
			Columns: []string{categorie.ParentColumn},
			Bidi:    false,
			Target: &sqlgraph.EdgeTarget{
				IDSpec: sqlgraph.NewFieldSpec(categorie.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:   categorie.EnfantsTable,
			Columns: []string{categorie.EnfantsColumn},
			Bidi:    false,
			Target: &sqlgraph.EdgeTarget{
				IDSpec: sqlgraph.NewFieldSpec(categorie.FieldID, field.TypeUUID),
			},
		}
		for _, k := range nodes {
			edge.Target.Nodes = append(edge.Target.Nodes, k)
		}
		_spec.Edges = append(_spec.Edges, edge)
	}
	return _node, _spec
}

// CategorieCreateBulk is the builder for creating many Categorie entities in bulk.
type CategorieCreateBulk struct {
	config
	err      error
	builders []*CategorieCreate
}

// Save creates the Categorie entities in the database.
func (_c *CategorieCreateBulk) Save(ctx context.Context) ([]*Categorie, error) {
	if _c.err != nil {
		return nil, _c.err
	}
	specs := make([]*sqlgraph.CreateSpec, len(_c.builders))
	nodes := make([]*Categorie, 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.(*CategorieMutation)
				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 *CategorieCreateBulk) SaveX(ctx context.Context) []*Categorie {
	v, err := _c.Save(ctx)
	if err != nil {
		panic(err)
	}
	return v
}

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

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