// 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/champpersonnalise"
	"gitea.maison43.duckdns.org/gilles/matosbox/internal/data/ent/lienobjetemplacement"
	"gitea.maison43.duckdns.org/gilles/matosbox/internal/data/ent/objet"
	"gitea.maison43.duckdns.org/gilles/matosbox/internal/data/ent/piecejointe"
	"github.com/google/uuid"
)

// ObjetCreate is the builder for creating a Objet entity.
type ObjetCreate struct {
	config
	mutation *ObjetMutation
	hooks    []Hook
}

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

// SetDescription sets the "description" field.
func (_c *ObjetCreate) SetDescription(v string) *ObjetCreate {
	_c.mutation.SetDescription(v)
	return _c
}

// SetNillableDescription sets the "description" field if the given value is not nil.
func (_c *ObjetCreate) SetNillableDescription(v *string) *ObjetCreate {
	if v != nil {
		_c.SetDescription(*v)
	}
	return _c
}

// SetQuantite sets the "quantite" field.
func (_c *ObjetCreate) SetQuantite(v int) *ObjetCreate {
	_c.mutation.SetQuantite(v)
	return _c
}

// SetNillableQuantite sets the "quantite" field if the given value is not nil.
func (_c *ObjetCreate) SetNillableQuantite(v *int) *ObjetCreate {
	if v != nil {
		_c.SetQuantite(*v)
	}
	return _c
}

// SetPrixAchat sets the "prix_achat" field.
func (_c *ObjetCreate) SetPrixAchat(v float64) *ObjetCreate {
	_c.mutation.SetPrixAchat(v)
	return _c
}

// SetNillablePrixAchat sets the "prix_achat" field if the given value is not nil.
func (_c *ObjetCreate) SetNillablePrixAchat(v *float64) *ObjetCreate {
	if v != nil {
		_c.SetPrixAchat(*v)
	}
	return _c
}

// SetDateAchat sets the "date_achat" field.
func (_c *ObjetCreate) SetDateAchat(v time.Time) *ObjetCreate {
	_c.mutation.SetDateAchat(v)
	return _c
}

// SetNillableDateAchat sets the "date_achat" field if the given value is not nil.
func (_c *ObjetCreate) SetNillableDateAchat(v *time.Time) *ObjetCreate {
	if v != nil {
		_c.SetDateAchat(*v)
	}
	return _c
}

// SetBoutique sets the "boutique" field.
func (_c *ObjetCreate) SetBoutique(v string) *ObjetCreate {
	_c.mutation.SetBoutique(v)
	return _c
}

// SetNillableBoutique sets the "boutique" field if the given value is not nil.
func (_c *ObjetCreate) SetNillableBoutique(v *string) *ObjetCreate {
	if v != nil {
		_c.SetBoutique(*v)
	}
	return _c
}

// SetNumeroSerie sets the "numero_serie" field.
func (_c *ObjetCreate) SetNumeroSerie(v string) *ObjetCreate {
	_c.mutation.SetNumeroSerie(v)
	return _c
}

// SetNillableNumeroSerie sets the "numero_serie" field if the given value is not nil.
func (_c *ObjetCreate) SetNillableNumeroSerie(v *string) *ObjetCreate {
	if v != nil {
		_c.SetNumeroSerie(*v)
	}
	return _c
}

// SetNumeroModele sets the "numero_modele" field.
func (_c *ObjetCreate) SetNumeroModele(v string) *ObjetCreate {
	_c.mutation.SetNumeroModele(v)
	return _c
}

// SetNillableNumeroModele sets the "numero_modele" field if the given value is not nil.
func (_c *ObjetCreate) SetNillableNumeroModele(v *string) *ObjetCreate {
	if v != nil {
		_c.SetNumeroModele(*v)
	}
	return _c
}

// SetFabricant sets the "fabricant" field.
func (_c *ObjetCreate) SetFabricant(v string) *ObjetCreate {
	_c.mutation.SetFabricant(v)
	return _c
}

// SetNillableFabricant sets the "fabricant" field if the given value is not nil.
func (_c *ObjetCreate) SetNillableFabricant(v *string) *ObjetCreate {
	if v != nil {
		_c.SetFabricant(*v)
	}
	return _c
}

// SetStatut sets the "statut" field.
func (_c *ObjetCreate) SetStatut(v objet.Statut) *ObjetCreate {
	_c.mutation.SetStatut(v)
	return _c
}

// SetNillableStatut sets the "statut" field if the given value is not nil.
func (_c *ObjetCreate) SetNillableStatut(v *objet.Statut) *ObjetCreate {
	if v != nil {
		_c.SetStatut(*v)
	}
	return _c
}

// SetCaracteristiques sets the "caracteristiques" field.
func (_c *ObjetCreate) SetCaracteristiques(v map[string]interface{}) *ObjetCreate {
	_c.mutation.SetCaracteristiques(v)
	return _c
}

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

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

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

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

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

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

// AddLiensEmplacementIDs adds the "liens_emplacements" edge to the LienObjetEmplacement entity by IDs.
func (_c *ObjetCreate) AddLiensEmplacementIDs(ids ...uuid.UUID) *ObjetCreate {
	_c.mutation.AddLiensEmplacementIDs(ids...)
	return _c
}

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

// AddChampsPersonnaliseIDs adds the "champs_personnalises" edge to the ChampPersonnalise entity by IDs.
func (_c *ObjetCreate) AddChampsPersonnaliseIDs(ids ...uuid.UUID) *ObjetCreate {
	_c.mutation.AddChampsPersonnaliseIDs(ids...)
	return _c
}

// AddChampsPersonnalises adds the "champs_personnalises" edges to the ChampPersonnalise entity.
func (_c *ObjetCreate) AddChampsPersonnalises(v ...*ChampPersonnalise) *ObjetCreate {
	ids := make([]uuid.UUID, len(v))
	for i := range v {
		ids[i] = v[i].ID
	}
	return _c.AddChampsPersonnaliseIDs(ids...)
}

// AddPiecesJointeIDs adds the "pieces_jointes" edge to the PieceJointe entity by IDs.
func (_c *ObjetCreate) AddPiecesJointeIDs(ids ...uuid.UUID) *ObjetCreate {
	_c.mutation.AddPiecesJointeIDs(ids...)
	return _c
}

// AddPiecesJointes adds the "pieces_jointes" edges to the PieceJointe entity.
func (_c *ObjetCreate) AddPiecesJointes(v ...*PieceJointe) *ObjetCreate {
	ids := make([]uuid.UUID, len(v))
	for i := range v {
		ids[i] = v[i].ID
	}
	return _c.AddPiecesJointeIDs(ids...)
}

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

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

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

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

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

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

func (_c *ObjetCreate) sqlSave(ctx context.Context) (*Objet, 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 *ObjetCreate) createSpec() (*Objet, *sqlgraph.CreateSpec) {
	var (
		_node = &Objet{config: _c.config}
		_spec = sqlgraph.NewCreateSpec(objet.Table, sqlgraph.NewFieldSpec(objet.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(objet.FieldNom, field.TypeString, value)
		_node.Nom = value
	}
	if value, ok := _c.mutation.Description(); ok {
		_spec.SetField(objet.FieldDescription, field.TypeString, value)
		_node.Description = &value
	}
	if value, ok := _c.mutation.Quantite(); ok {
		_spec.SetField(objet.FieldQuantite, field.TypeInt, value)
		_node.Quantite = value
	}
	if value, ok := _c.mutation.PrixAchat(); ok {
		_spec.SetField(objet.FieldPrixAchat, field.TypeFloat64, value)
		_node.PrixAchat = &value
	}
	if value, ok := _c.mutation.DateAchat(); ok {
		_spec.SetField(objet.FieldDateAchat, field.TypeTime, value)
		_node.DateAchat = &value
	}
	if value, ok := _c.mutation.Boutique(); ok {
		_spec.SetField(objet.FieldBoutique, field.TypeString, value)
		_node.Boutique = &value
	}
	if value, ok := _c.mutation.NumeroSerie(); ok {
		_spec.SetField(objet.FieldNumeroSerie, field.TypeString, value)
		_node.NumeroSerie = &value
	}
	if value, ok := _c.mutation.NumeroModele(); ok {
		_spec.SetField(objet.FieldNumeroModele, field.TypeString, value)
		_node.NumeroModele = &value
	}
	if value, ok := _c.mutation.Fabricant(); ok {
		_spec.SetField(objet.FieldFabricant, field.TypeString, value)
		_node.Fabricant = &value
	}
	if value, ok := _c.mutation.Statut(); ok {
		_spec.SetField(objet.FieldStatut, field.TypeEnum, value)
		_node.Statut = value
	}
	if value, ok := _c.mutation.Caracteristiques(); ok {
		_spec.SetField(objet.FieldCaracteristiques, field.TypeJSON, value)
		_node.Caracteristiques = value
	}
	if value, ok := _c.mutation.CreatedAt(); ok {
		_spec.SetField(objet.FieldCreatedAt, field.TypeTime, value)
		_node.CreatedAt = value
	}
	if value, ok := _c.mutation.UpdatedAt(); ok {
		_spec.SetField(objet.FieldUpdatedAt, field.TypeTime, value)
		_node.UpdatedAt = value
	}
	if nodes := _c.mutation.LiensEmplacementsIDs(); len(nodes) > 0 {
		edge := &sqlgraph.EdgeSpec{
			Rel:     sqlgraph.O2M,
			Inverse: false,
			Table:   objet.LiensEmplacementsTable,
			Columns: []string{objet.LiensEmplacementsColumn},
			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)
	}
	if nodes := _c.mutation.ChampsPersonnalisesIDs(); len(nodes) > 0 {
		edge := &sqlgraph.EdgeSpec{
			Rel:     sqlgraph.O2M,
			Inverse: false,
			Table:   objet.ChampsPersonnalisesTable,
			Columns: []string{objet.ChampsPersonnalisesColumn},
			Bidi:    false,
			Target: &sqlgraph.EdgeTarget{
				IDSpec: sqlgraph.NewFieldSpec(champpersonnalise.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.PiecesJointesIDs(); len(nodes) > 0 {
		edge := &sqlgraph.EdgeSpec{
			Rel:     sqlgraph.O2M,
			Inverse: false,
			Table:   objet.PiecesJointesTable,
			Columns: []string{objet.PiecesJointesColumn},
			Bidi:    false,
			Target: &sqlgraph.EdgeTarget{
				IDSpec: sqlgraph.NewFieldSpec(piecejointe.FieldID, field.TypeUUID),
			},
		}
		for _, k := range nodes {
			edge.Target.Nodes = append(edge.Target.Nodes, k)
		}
		_spec.Edges = append(_spec.Edges, edge)
	}
	return _node, _spec
}

// ObjetCreateBulk is the builder for creating many Objet entities in bulk.
type ObjetCreateBulk struct {
	config
	err      error
	builders []*ObjetCreate
}

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

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

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