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

// PieceJointeCreate is the builder for creating a PieceJointe entity.
type PieceJointeCreate struct {
	config
	mutation *PieceJointeMutation
	hooks    []Hook
}

// SetObjetID sets the "objet_id" field.
func (_c *PieceJointeCreate) SetObjetID(v uuid.UUID) *PieceJointeCreate {
	_c.mutation.SetObjetID(v)
	return _c
}

// SetNomFichier sets the "nom_fichier" field.
func (_c *PieceJointeCreate) SetNomFichier(v string) *PieceJointeCreate {
	_c.mutation.SetNomFichier(v)
	return _c
}

// SetChemin sets the "chemin" field.
func (_c *PieceJointeCreate) SetChemin(v string) *PieceJointeCreate {
	_c.mutation.SetChemin(v)
	return _c
}

// SetTypeMime sets the "type_mime" field.
func (_c *PieceJointeCreate) SetTypeMime(v string) *PieceJointeCreate {
	_c.mutation.SetTypeMime(v)
	return _c
}

// SetEstPrincipale sets the "est_principale" field.
func (_c *PieceJointeCreate) SetEstPrincipale(v bool) *PieceJointeCreate {
	_c.mutation.SetEstPrincipale(v)
	return _c
}

// SetNillableEstPrincipale sets the "est_principale" field if the given value is not nil.
func (_c *PieceJointeCreate) SetNillableEstPrincipale(v *bool) *PieceJointeCreate {
	if v != nil {
		_c.SetEstPrincipale(*v)
	}
	return _c
}

// SetCategorie sets the "categorie" field.
func (_c *PieceJointeCreate) SetCategorie(v piecejointe.Categorie) *PieceJointeCreate {
	_c.mutation.SetCategorie(v)
	return _c
}

// SetNillableCategorie sets the "categorie" field if the given value is not nil.
func (_c *PieceJointeCreate) SetNillableCategorie(v *piecejointe.Categorie) *PieceJointeCreate {
	if v != nil {
		_c.SetCategorie(*v)
	}
	return _c
}

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

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

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

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

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

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

// SetObjet sets the "objet" edge to the Objet entity.
func (_c *PieceJointeCreate) SetObjet(v *Objet) *PieceJointeCreate {
	return _c.SetObjetID(v.ID)
}

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

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

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

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

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

// check runs all checks and user-defined validators on the builder.
func (_c *PieceJointeCreate) check() error {
	if _, ok := _c.mutation.ObjetID(); !ok {
		return &ValidationError{Name: "objet_id", err: errors.New(`ent: missing required field "PieceJointe.objet_id"`)}
	}
	if _, ok := _c.mutation.NomFichier(); !ok {
		return &ValidationError{Name: "nom_fichier", err: errors.New(`ent: missing required field "PieceJointe.nom_fichier"`)}
	}
	if v, ok := _c.mutation.NomFichier(); ok {
		if err := piecejointe.NomFichierValidator(v); err != nil {
			return &ValidationError{Name: "nom_fichier", err: fmt.Errorf(`ent: validator failed for field "PieceJointe.nom_fichier": %w`, err)}
		}
	}
	if _, ok := _c.mutation.Chemin(); !ok {
		return &ValidationError{Name: "chemin", err: errors.New(`ent: missing required field "PieceJointe.chemin"`)}
	}
	if v, ok := _c.mutation.Chemin(); ok {
		if err := piecejointe.CheminValidator(v); err != nil {
			return &ValidationError{Name: "chemin", err: fmt.Errorf(`ent: validator failed for field "PieceJointe.chemin": %w`, err)}
		}
	}
	if _, ok := _c.mutation.TypeMime(); !ok {
		return &ValidationError{Name: "type_mime", err: errors.New(`ent: missing required field "PieceJointe.type_mime"`)}
	}
	if v, ok := _c.mutation.TypeMime(); ok {
		if err := piecejointe.TypeMimeValidator(v); err != nil {
			return &ValidationError{Name: "type_mime", err: fmt.Errorf(`ent: validator failed for field "PieceJointe.type_mime": %w`, err)}
		}
	}
	if _, ok := _c.mutation.EstPrincipale(); !ok {
		return &ValidationError{Name: "est_principale", err: errors.New(`ent: missing required field "PieceJointe.est_principale"`)}
	}
	if _, ok := _c.mutation.Categorie(); !ok {
		return &ValidationError{Name: "categorie", err: errors.New(`ent: missing required field "PieceJointe.categorie"`)}
	}
	if v, ok := _c.mutation.Categorie(); ok {
		if err := piecejointe.CategorieValidator(v); err != nil {
			return &ValidationError{Name: "categorie", err: fmt.Errorf(`ent: validator failed for field "PieceJointe.categorie": %w`, err)}
		}
	}
	if _, ok := _c.mutation.CreatedAt(); !ok {
		return &ValidationError{Name: "created_at", err: errors.New(`ent: missing required field "PieceJointe.created_at"`)}
	}
	if _, ok := _c.mutation.UpdatedAt(); !ok {
		return &ValidationError{Name: "updated_at", err: errors.New(`ent: missing required field "PieceJointe.updated_at"`)}
	}
	if len(_c.mutation.ObjetIDs()) == 0 {
		return &ValidationError{Name: "objet", err: errors.New(`ent: missing required edge "PieceJointe.objet"`)}
	}
	return nil
}

func (_c *PieceJointeCreate) sqlSave(ctx context.Context) (*PieceJointe, 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 *PieceJointeCreate) createSpec() (*PieceJointe, *sqlgraph.CreateSpec) {
	var (
		_node = &PieceJointe{config: _c.config}
		_spec = sqlgraph.NewCreateSpec(piecejointe.Table, sqlgraph.NewFieldSpec(piecejointe.FieldID, field.TypeUUID))
	)
	if id, ok := _c.mutation.ID(); ok {
		_node.ID = id
		_spec.ID.Value = &id
	}
	if value, ok := _c.mutation.NomFichier(); ok {
		_spec.SetField(piecejointe.FieldNomFichier, field.TypeString, value)
		_node.NomFichier = value
	}
	if value, ok := _c.mutation.Chemin(); ok {
		_spec.SetField(piecejointe.FieldChemin, field.TypeString, value)
		_node.Chemin = value
	}
	if value, ok := _c.mutation.TypeMime(); ok {
		_spec.SetField(piecejointe.FieldTypeMime, field.TypeString, value)
		_node.TypeMime = value
	}
	if value, ok := _c.mutation.EstPrincipale(); ok {
		_spec.SetField(piecejointe.FieldEstPrincipale, field.TypeBool, value)
		_node.EstPrincipale = value
	}
	if value, ok := _c.mutation.Categorie(); ok {
		_spec.SetField(piecejointe.FieldCategorie, field.TypeEnum, value)
		_node.Categorie = value
	}
	if value, ok := _c.mutation.CreatedAt(); ok {
		_spec.SetField(piecejointe.FieldCreatedAt, field.TypeTime, value)
		_node.CreatedAt = value
	}
	if value, ok := _c.mutation.UpdatedAt(); ok {
		_spec.SetField(piecejointe.FieldUpdatedAt, field.TypeTime, value)
		_node.UpdatedAt = value
	}
	if nodes := _c.mutation.ObjetIDs(); len(nodes) > 0 {
		edge := &sqlgraph.EdgeSpec{
			Rel:     sqlgraph.M2O,
			Inverse: true,
			Table:   piecejointe.ObjetTable,
			Columns: []string{piecejointe.ObjetColumn},
			Bidi:    false,
			Target: &sqlgraph.EdgeTarget{
				IDSpec: sqlgraph.NewFieldSpec(objet.FieldID, field.TypeUUID),
			},
		}
		for _, k := range nodes {
			edge.Target.Nodes = append(edge.Target.Nodes, k)
		}
		_node.ObjetID = nodes[0]
		_spec.Edges = append(_spec.Edges, edge)
	}
	return _node, _spec
}

// PieceJointeCreateBulk is the builder for creating many PieceJointe entities in bulk.
type PieceJointeCreateBulk struct {
	config
	err      error
	builders []*PieceJointeCreate
}

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

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

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