// Code generated by ent, DO NOT EDIT.

package ent

import (
	"PasswordManager/ent/note"
	"PasswordManager/ent/password"
	"PasswordManager/ent/user"
	"PasswordManager/ent/vault"
	"context"
	"errors"
	"fmt"
	"time"

	"entgo.io/ent/dialect/sql/sqlgraph"
	"entgo.io/ent/schema/field"
	"github.com/google/uuid"
)

// VaultCreate is the builder for creating a Vault entity.
type VaultCreate struct {
	config
	mutation *VaultMutation
	hooks    []Hook
}

// SetCreatedAt sets the "createdAt" field.
func (vc *VaultCreate) SetCreatedAt(t time.Time) *VaultCreate {
	vc.mutation.SetCreatedAt(t)
	return vc
}

// SetNillableCreatedAt sets the "createdAt" field if the given value is not nil.
func (vc *VaultCreate) SetNillableCreatedAt(t *time.Time) *VaultCreate {
	if t != nil {
		vc.SetCreatedAt(*t)
	}
	return vc
}

// SetName sets the "name" field.
func (vc *VaultCreate) SetName(b []byte) *VaultCreate {
	vc.mutation.SetName(b)
	return vc
}

// SetNameIv sets the "nameIv" field.
func (vc *VaultCreate) SetNameIv(b []byte) *VaultCreate {
	vc.mutation.SetNameIv(b)
	return vc
}

// SetColour sets the "colour" field.
func (vc *VaultCreate) SetColour(b []byte) *VaultCreate {
	vc.mutation.SetColour(b)
	return vc
}

// SetColourIv sets the "colourIv" field.
func (vc *VaultCreate) SetColourIv(b []byte) *VaultCreate {
	vc.mutation.SetColourIv(b)
	return vc
}

// SetID sets the "id" field.
func (vc *VaultCreate) SetID(u uuid.UUID) *VaultCreate {
	vc.mutation.SetID(u)
	return vc
}

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

// AddPasswordIDs adds the "passwords" edge to the Password entity by IDs.
func (vc *VaultCreate) AddPasswordIDs(ids ...uuid.UUID) *VaultCreate {
	vc.mutation.AddPasswordIDs(ids...)
	return vc
}

// AddPasswords adds the "passwords" edges to the Password entity.
func (vc *VaultCreate) AddPasswords(p ...*Password) *VaultCreate {
	ids := make([]uuid.UUID, len(p))
	for i := range p {
		ids[i] = p[i].ID
	}
	return vc.AddPasswordIDs(ids...)
}

// AddNoteIDs adds the "notes" edge to the Note entity by IDs.
func (vc *VaultCreate) AddNoteIDs(ids ...uuid.UUID) *VaultCreate {
	vc.mutation.AddNoteIDs(ids...)
	return vc
}

// AddNotes adds the "notes" edges to the Note entity.
func (vc *VaultCreate) AddNotes(n ...*Note) *VaultCreate {
	ids := make([]uuid.UUID, len(n))
	for i := range n {
		ids[i] = n[i].ID
	}
	return vc.AddNoteIDs(ids...)
}

// SetUserID sets the "user" edge to the User entity by ID.
func (vc *VaultCreate) SetUserID(id uuid.UUID) *VaultCreate {
	vc.mutation.SetUserID(id)
	return vc
}

// SetNillableUserID sets the "user" edge to the User entity by ID if the given value is not nil.
func (vc *VaultCreate) SetNillableUserID(id *uuid.UUID) *VaultCreate {
	if id != nil {
		vc = vc.SetUserID(*id)
	}
	return vc
}

// SetUser sets the "user" edge to the User entity.
func (vc *VaultCreate) SetUser(u *User) *VaultCreate {
	return vc.SetUserID(u.ID)
}

// Mutation returns the VaultMutation object of the builder.
func (vc *VaultCreate) Mutation() *VaultMutation {
	return vc.mutation
}

// Save creates the Vault in the database.
func (vc *VaultCreate) Save(ctx context.Context) (*Vault, error) {
	vc.defaults()
	return withHooks[*Vault, VaultMutation](ctx, vc.sqlSave, vc.mutation, vc.hooks)
}

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

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

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

// defaults sets the default values of the builder before save.
func (vc *VaultCreate) defaults() {
	if _, ok := vc.mutation.CreatedAt(); !ok {
		v := vault.DefaultCreatedAt()
		vc.mutation.SetCreatedAt(v)
	}
	if _, ok := vc.mutation.ID(); !ok {
		v := vault.DefaultID()
		vc.mutation.SetID(v)
	}
}

// check runs all checks and user-defined validators on the builder.
func (vc *VaultCreate) check() error {
	if _, ok := vc.mutation.CreatedAt(); !ok {
		return &ValidationError{Name: "createdAt", err: errors.New(`ent: missing required field "Vault.createdAt"`)}
	}
	if _, ok := vc.mutation.Name(); !ok {
		return &ValidationError{Name: "name", err: errors.New(`ent: missing required field "Vault.name"`)}
	}
	if v, ok := vc.mutation.Name(); ok {
		if err := vault.NameValidator(v); err != nil {
			return &ValidationError{Name: "name", err: fmt.Errorf(`ent: validator failed for field "Vault.name": %w`, err)}
		}
	}
	if _, ok := vc.mutation.NameIv(); !ok {
		return &ValidationError{Name: "nameIv", err: errors.New(`ent: missing required field "Vault.nameIv"`)}
	}
	if v, ok := vc.mutation.NameIv(); ok {
		if err := vault.NameIvValidator(v); err != nil {
			return &ValidationError{Name: "nameIv", err: fmt.Errorf(`ent: validator failed for field "Vault.nameIv": %w`, err)}
		}
	}
	if _, ok := vc.mutation.Colour(); !ok {
		return &ValidationError{Name: "colour", err: errors.New(`ent: missing required field "Vault.colour"`)}
	}
	if v, ok := vc.mutation.Colour(); ok {
		if err := vault.ColourValidator(v); err != nil {
			return &ValidationError{Name: "colour", err: fmt.Errorf(`ent: validator failed for field "Vault.colour": %w`, err)}
		}
	}
	if _, ok := vc.mutation.ColourIv(); !ok {
		return &ValidationError{Name: "colourIv", err: errors.New(`ent: missing required field "Vault.colourIv"`)}
	}
	if v, ok := vc.mutation.ColourIv(); ok {
		if err := vault.ColourIvValidator(v); err != nil {
			return &ValidationError{Name: "colourIv", err: fmt.Errorf(`ent: validator failed for field "Vault.colourIv": %w`, err)}
		}
	}
	return nil
}

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

func (vc *VaultCreate) createSpec() (*Vault, *sqlgraph.CreateSpec) {
	var (
		_node = &Vault{config: vc.config}
		_spec = sqlgraph.NewCreateSpec(vault.Table, sqlgraph.NewFieldSpec(vault.FieldID, field.TypeUUID))
	)
	if id, ok := vc.mutation.ID(); ok {
		_node.ID = id
		_spec.ID.Value = &id
	}
	if value, ok := vc.mutation.CreatedAt(); ok {
		_spec.SetField(vault.FieldCreatedAt, field.TypeTime, value)
		_node.CreatedAt = value
	}
	if value, ok := vc.mutation.Name(); ok {
		_spec.SetField(vault.FieldName, field.TypeBytes, value)
		_node.Name = value
	}
	if value, ok := vc.mutation.NameIv(); ok {
		_spec.SetField(vault.FieldNameIv, field.TypeBytes, value)
		_node.NameIv = value
	}
	if value, ok := vc.mutation.Colour(); ok {
		_spec.SetField(vault.FieldColour, field.TypeBytes, value)
		_node.Colour = value
	}
	if value, ok := vc.mutation.ColourIv(); ok {
		_spec.SetField(vault.FieldColourIv, field.TypeBytes, value)
		_node.ColourIv = value
	}
	if nodes := vc.mutation.PasswordsIDs(); len(nodes) > 0 {
		edge := &sqlgraph.EdgeSpec{
			Rel:     sqlgraph.O2M,
			Inverse: false,
			Table:   vault.PasswordsTable,
			Columns: []string{vault.PasswordsColumn},
			Bidi:    false,
			Target: &sqlgraph.EdgeTarget{
				IDSpec: sqlgraph.NewFieldSpec(password.FieldID, field.TypeUUID),
			},
		}
		for _, k := range nodes {
			edge.Target.Nodes = append(edge.Target.Nodes, k)
		}
		_spec.Edges = append(_spec.Edges, edge)
	}
	if nodes := vc.mutation.NotesIDs(); len(nodes) > 0 {
		edge := &sqlgraph.EdgeSpec{
			Rel:     sqlgraph.O2M,
			Inverse: false,
			Table:   vault.NotesTable,
			Columns: []string{vault.NotesColumn},
			Bidi:    false,
			Target: &sqlgraph.EdgeTarget{
				IDSpec: sqlgraph.NewFieldSpec(note.FieldID, field.TypeUUID),
			},
		}
		for _, k := range nodes {
			edge.Target.Nodes = append(edge.Target.Nodes, k)
		}
		_spec.Edges = append(_spec.Edges, edge)
	}
	if nodes := vc.mutation.UserIDs(); len(nodes) > 0 {
		edge := &sqlgraph.EdgeSpec{
			Rel:     sqlgraph.M2O,
			Inverse: true,
			Table:   vault.UserTable,
			Columns: []string{vault.UserColumn},
			Bidi:    false,
			Target: &sqlgraph.EdgeTarget{
				IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeUUID),
			},
		}
		for _, k := range nodes {
			edge.Target.Nodes = append(edge.Target.Nodes, k)
		}
		_node.user_vaults = &nodes[0]
		_spec.Edges = append(_spec.Edges, edge)
	}
	return _node, _spec
}

// VaultCreateBulk is the builder for creating many Vault entities in bulk.
type VaultCreateBulk struct {
	config
	builders []*VaultCreate
}

// Save creates the Vault entities in the database.
func (vcb *VaultCreateBulk) Save(ctx context.Context) ([]*Vault, error) {
	specs := make([]*sqlgraph.CreateSpec, len(vcb.builders))
	nodes := make([]*Vault, len(vcb.builders))
	mutators := make([]Mutator, len(vcb.builders))
	for i := range vcb.builders {
		func(i int, root context.Context) {
			builder := vcb.builders[i]
			builder.defaults()
			var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
				mutation, ok := m.(*VaultMutation)
				if !ok {
					return nil, fmt.Errorf("unexpected mutation type %T", m)
				}
				if err := builder.check(); err != nil {
					return nil, err
				}
				builder.mutation = mutation
				nodes[i], specs[i] = builder.createSpec()
				var err error
				if i < len(mutators)-1 {
					_, err = mutators[i+1].Mutate(root, vcb.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, vcb.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, vcb.builders[0].mutation); err != nil {
			return nil, err
		}
	}
	return nodes, nil
}

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

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

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