// Code generated by ent, DO NOT EDIT.

package ent

import (
	"PasswordManager/ent/challenge"
	"PasswordManager/ent/totpcredential"
	"PasswordManager/ent/user"
	"context"
	"errors"
	"fmt"

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

// TotpCredentialCreate is the builder for creating a TotpCredential entity.
type TotpCredentialCreate struct {
	config
	mutation *TotpCredentialMutation
	hooks    []Hook
}

// SetSecret sets the "secret" field.
func (tcc *TotpCredentialCreate) SetSecret(s string) *TotpCredentialCreate {
	tcc.mutation.SetSecret(s)
	return tcc
}

// SetValidated sets the "validated" field.
func (tcc *TotpCredentialCreate) SetValidated(b bool) *TotpCredentialCreate {
	tcc.mutation.SetValidated(b)
	return tcc
}

// SetNillableValidated sets the "validated" field if the given value is not nil.
func (tcc *TotpCredentialCreate) SetNillableValidated(b *bool) *TotpCredentialCreate {
	if b != nil {
		tcc.SetValidated(*b)
	}
	return tcc
}

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

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

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

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

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

// SetChallengeID sets the "challenge" edge to the Challenge entity by ID.
func (tcc *TotpCredentialCreate) SetChallengeID(id uuid.UUID) *TotpCredentialCreate {
	tcc.mutation.SetChallengeID(id)
	return tcc
}

// SetNillableChallengeID sets the "challenge" edge to the Challenge entity by ID if the given value is not nil.
func (tcc *TotpCredentialCreate) SetNillableChallengeID(id *uuid.UUID) *TotpCredentialCreate {
	if id != nil {
		tcc = tcc.SetChallengeID(*id)
	}
	return tcc
}

// SetChallenge sets the "challenge" edge to the Challenge entity.
func (tcc *TotpCredentialCreate) SetChallenge(c *Challenge) *TotpCredentialCreate {
	return tcc.SetChallengeID(c.ID)
}

// Mutation returns the TotpCredentialMutation object of the builder.
func (tcc *TotpCredentialCreate) Mutation() *TotpCredentialMutation {
	return tcc.mutation
}

// Save creates the TotpCredential in the database.
func (tcc *TotpCredentialCreate) Save(ctx context.Context) (*TotpCredential, error) {
	tcc.defaults()
	return withHooks[*TotpCredential, TotpCredentialMutation](ctx, tcc.sqlSave, tcc.mutation, tcc.hooks)
}

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

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

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

// defaults sets the default values of the builder before save.
func (tcc *TotpCredentialCreate) defaults() {
	if _, ok := tcc.mutation.Validated(); !ok {
		v := totpcredential.DefaultValidated
		tcc.mutation.SetValidated(v)
	}
	if _, ok := tcc.mutation.ID(); !ok {
		v := totpcredential.DefaultID()
		tcc.mutation.SetID(v)
	}
}

// check runs all checks and user-defined validators on the builder.
func (tcc *TotpCredentialCreate) check() error {
	if _, ok := tcc.mutation.Secret(); !ok {
		return &ValidationError{Name: "secret", err: errors.New(`ent: missing required field "TotpCredential.secret"`)}
	}
	if v, ok := tcc.mutation.Secret(); ok {
		if err := totpcredential.SecretValidator(v); err != nil {
			return &ValidationError{Name: "secret", err: fmt.Errorf(`ent: validator failed for field "TotpCredential.secret": %w`, err)}
		}
	}
	if _, ok := tcc.mutation.Validated(); !ok {
		return &ValidationError{Name: "validated", err: errors.New(`ent: missing required field "TotpCredential.validated"`)}
	}
	return nil
}

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

func (tcc *TotpCredentialCreate) createSpec() (*TotpCredential, *sqlgraph.CreateSpec) {
	var (
		_node = &TotpCredential{config: tcc.config}
		_spec = sqlgraph.NewCreateSpec(totpcredential.Table, sqlgraph.NewFieldSpec(totpcredential.FieldID, field.TypeUUID))
	)
	if id, ok := tcc.mutation.ID(); ok {
		_node.ID = id
		_spec.ID.Value = &id
	}
	if value, ok := tcc.mutation.Secret(); ok {
		_spec.SetField(totpcredential.FieldSecret, field.TypeString, value)
		_node.Secret = value
	}
	if value, ok := tcc.mutation.Validated(); ok {
		_spec.SetField(totpcredential.FieldValidated, field.TypeBool, value)
		_node.Validated = value
	}
	if nodes := tcc.mutation.UserIDs(); len(nodes) > 0 {
		edge := &sqlgraph.EdgeSpec{
			Rel:     sqlgraph.O2O,
			Inverse: true,
			Table:   totpcredential.UserTable,
			Columns: []string{totpcredential.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_totp_credential = &nodes[0]
		_spec.Edges = append(_spec.Edges, edge)
	}
	if nodes := tcc.mutation.ChallengeIDs(); len(nodes) > 0 {
		edge := &sqlgraph.EdgeSpec{
			Rel:     sqlgraph.O2O,
			Inverse: true,
			Table:   totpcredential.ChallengeTable,
			Columns: []string{totpcredential.ChallengeColumn},
			Bidi:    false,
			Target: &sqlgraph.EdgeTarget{
				IDSpec: sqlgraph.NewFieldSpec(challenge.FieldID, field.TypeUUID),
			},
		}
		for _, k := range nodes {
			edge.Target.Nodes = append(edge.Target.Nodes, k)
		}
		_node.challenge_totp_credential = &nodes[0]
		_spec.Edges = append(_spec.Edges, edge)
	}
	return _node, _spec
}

// TotpCredentialCreateBulk is the builder for creating many TotpCredential entities in bulk.
type TotpCredentialCreateBulk struct {
	config
	builders []*TotpCredentialCreate
}

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

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

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

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