// Code generated by ent, DO NOT EDIT.

package ent

import (
	"PasswordManager/ent/challenge"
	"PasswordManager/ent/session"
	"PasswordManager/ent/totpcredential"
	"PasswordManager/ent/user"
	"PasswordManager/ent/vault"
	"PasswordManager/ent/webauthncredential"
	"PasswordManager/ent/webauthnregisterchallenge"
	"context"
	"errors"
	"fmt"

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

// UserCreate is the builder for creating a User entity.
type UserCreate struct {
	config
	mutation *UserMutation
	hooks    []Hook
}

// SetEmail sets the "email" field.
func (uc *UserCreate) SetEmail(s string) *UserCreate {
	uc.mutation.SetEmail(s)
	return uc
}

// SetStrengthenedMasterHash sets the "strengthenedMasterHash" field.
func (uc *UserCreate) SetStrengthenedMasterHash(b []byte) *UserCreate {
	uc.mutation.SetStrengthenedMasterHash(b)
	return uc
}

// SetStrengthenedMasterHashSalt sets the "strengthenedMasterHashSalt" field.
func (uc *UserCreate) SetStrengthenedMasterHashSalt(b []byte) *UserCreate {
	uc.mutation.SetStrengthenedMasterHashSalt(b)
	return uc
}

// SetProtectedDatabaseKey sets the "protectedDatabaseKey" field.
func (uc *UserCreate) SetProtectedDatabaseKey(b []byte) *UserCreate {
	uc.mutation.SetProtectedDatabaseKey(b)
	return uc
}

// SetProtectedDatabaseKeyIv sets the "protectedDatabaseKeyIv" field.
func (uc *UserCreate) SetProtectedDatabaseKeyIv(b []byte) *UserCreate {
	uc.mutation.SetProtectedDatabaseKeyIv(b)
	return uc
}

// SetWebauthnEnabled sets the "webauthnEnabled" field.
func (uc *UserCreate) SetWebauthnEnabled(b bool) *UserCreate {
	uc.mutation.SetWebauthnEnabled(b)
	return uc
}

// SetNillableWebauthnEnabled sets the "webauthnEnabled" field if the given value is not nil.
func (uc *UserCreate) SetNillableWebauthnEnabled(b *bool) *UserCreate {
	if b != nil {
		uc.SetWebauthnEnabled(*b)
	}
	return uc
}

// SetTotpEnabled sets the "totpEnabled" field.
func (uc *UserCreate) SetTotpEnabled(b bool) *UserCreate {
	uc.mutation.SetTotpEnabled(b)
	return uc
}

// SetNillableTotpEnabled sets the "totpEnabled" field if the given value is not nil.
func (uc *UserCreate) SetNillableTotpEnabled(b *bool) *UserCreate {
	if b != nil {
		uc.SetTotpEnabled(*b)
	}
	return uc
}

// SetVerified sets the "verified" field.
func (uc *UserCreate) SetVerified(b bool) *UserCreate {
	uc.mutation.SetVerified(b)
	return uc
}

// SetNillableVerified sets the "verified" field if the given value is not nil.
func (uc *UserCreate) SetNillableVerified(b *bool) *UserCreate {
	if b != nil {
		uc.SetVerified(*b)
	}
	return uc
}

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

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

// SetTotpCredentialID sets the "totpCredential" edge to the TotpCredential entity by ID.
func (uc *UserCreate) SetTotpCredentialID(id uuid.UUID) *UserCreate {
	uc.mutation.SetTotpCredentialID(id)
	return uc
}

// SetNillableTotpCredentialID sets the "totpCredential" edge to the TotpCredential entity by ID if the given value is not nil.
func (uc *UserCreate) SetNillableTotpCredentialID(id *uuid.UUID) *UserCreate {
	if id != nil {
		uc = uc.SetTotpCredentialID(*id)
	}
	return uc
}

// SetTotpCredential sets the "totpCredential" edge to the TotpCredential entity.
func (uc *UserCreate) SetTotpCredential(t *TotpCredential) *UserCreate {
	return uc.SetTotpCredentialID(t.ID)
}

// AddWebauthnCredentialIDs adds the "webauthnCredentials" edge to the WebAuthnCredential entity by IDs.
func (uc *UserCreate) AddWebauthnCredentialIDs(ids ...uuid.UUID) *UserCreate {
	uc.mutation.AddWebauthnCredentialIDs(ids...)
	return uc
}

// AddWebauthnCredentials adds the "webauthnCredentials" edges to the WebAuthnCredential entity.
func (uc *UserCreate) AddWebauthnCredentials(w ...*WebAuthnCredential) *UserCreate {
	ids := make([]uuid.UUID, len(w))
	for i := range w {
		ids[i] = w[i].ID
	}
	return uc.AddWebauthnCredentialIDs(ids...)
}

// AddWebauthnRegisterChallengeIDs adds the "webauthnRegisterChallenges" edge to the WebAuthnRegisterChallenge entity by IDs.
func (uc *UserCreate) AddWebauthnRegisterChallengeIDs(ids ...uuid.UUID) *UserCreate {
	uc.mutation.AddWebauthnRegisterChallengeIDs(ids...)
	return uc
}

// AddWebauthnRegisterChallenges adds the "webauthnRegisterChallenges" edges to the WebAuthnRegisterChallenge entity.
func (uc *UserCreate) AddWebauthnRegisterChallenges(w ...*WebAuthnRegisterChallenge) *UserCreate {
	ids := make([]uuid.UUID, len(w))
	for i := range w {
		ids[i] = w[i].ID
	}
	return uc.AddWebauthnRegisterChallengeIDs(ids...)
}

// AddVaultIDs adds the "vaults" edge to the Vault entity by IDs.
func (uc *UserCreate) AddVaultIDs(ids ...uuid.UUID) *UserCreate {
	uc.mutation.AddVaultIDs(ids...)
	return uc
}

// AddVaults adds the "vaults" edges to the Vault entity.
func (uc *UserCreate) AddVaults(v ...*Vault) *UserCreate {
	ids := make([]uuid.UUID, len(v))
	for i := range v {
		ids[i] = v[i].ID
	}
	return uc.AddVaultIDs(ids...)
}

// AddSessionIDs adds the "sessions" edge to the Session entity by IDs.
func (uc *UserCreate) AddSessionIDs(ids ...uuid.UUID) *UserCreate {
	uc.mutation.AddSessionIDs(ids...)
	return uc
}

// AddSessions adds the "sessions" edges to the Session entity.
func (uc *UserCreate) AddSessions(s ...*Session) *UserCreate {
	ids := make([]uuid.UUID, len(s))
	for i := range s {
		ids[i] = s[i].ID
	}
	return uc.AddSessionIDs(ids...)
}

// AddChallengeIDs adds the "challenges" edge to the Challenge entity by IDs.
func (uc *UserCreate) AddChallengeIDs(ids ...uuid.UUID) *UserCreate {
	uc.mutation.AddChallengeIDs(ids...)
	return uc
}

// AddChallenges adds the "challenges" edges to the Challenge entity.
func (uc *UserCreate) AddChallenges(c ...*Challenge) *UserCreate {
	ids := make([]uuid.UUID, len(c))
	for i := range c {
		ids[i] = c[i].ID
	}
	return uc.AddChallengeIDs(ids...)
}

// Mutation returns the UserMutation object of the builder.
func (uc *UserCreate) Mutation() *UserMutation {
	return uc.mutation
}

// Save creates the User in the database.
func (uc *UserCreate) Save(ctx context.Context) (*User, error) {
	uc.defaults()
	return withHooks[*User, UserMutation](ctx, uc.sqlSave, uc.mutation, uc.hooks)
}

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

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

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

// defaults sets the default values of the builder before save.
func (uc *UserCreate) defaults() {
	if _, ok := uc.mutation.WebauthnEnabled(); !ok {
		v := user.DefaultWebauthnEnabled
		uc.mutation.SetWebauthnEnabled(v)
	}
	if _, ok := uc.mutation.TotpEnabled(); !ok {
		v := user.DefaultTotpEnabled
		uc.mutation.SetTotpEnabled(v)
	}
	if _, ok := uc.mutation.Verified(); !ok {
		v := user.DefaultVerified
		uc.mutation.SetVerified(v)
	}
	if _, ok := uc.mutation.ID(); !ok {
		v := user.DefaultID()
		uc.mutation.SetID(v)
	}
}

// check runs all checks and user-defined validators on the builder.
func (uc *UserCreate) check() error {
	if _, ok := uc.mutation.Email(); !ok {
		return &ValidationError{Name: "email", err: errors.New(`ent: missing required field "User.email"`)}
	}
	if _, ok := uc.mutation.StrengthenedMasterHash(); !ok {
		return &ValidationError{Name: "strengthenedMasterHash", err: errors.New(`ent: missing required field "User.strengthenedMasterHash"`)}
	}
	if v, ok := uc.mutation.StrengthenedMasterHash(); ok {
		if err := user.StrengthenedMasterHashValidator(v); err != nil {
			return &ValidationError{Name: "strengthenedMasterHash", err: fmt.Errorf(`ent: validator failed for field "User.strengthenedMasterHash": %w`, err)}
		}
	}
	if _, ok := uc.mutation.StrengthenedMasterHashSalt(); !ok {
		return &ValidationError{Name: "strengthenedMasterHashSalt", err: errors.New(`ent: missing required field "User.strengthenedMasterHashSalt"`)}
	}
	if v, ok := uc.mutation.StrengthenedMasterHashSalt(); ok {
		if err := user.StrengthenedMasterHashSaltValidator(v); err != nil {
			return &ValidationError{Name: "strengthenedMasterHashSalt", err: fmt.Errorf(`ent: validator failed for field "User.strengthenedMasterHashSalt": %w`, err)}
		}
	}
	if _, ok := uc.mutation.ProtectedDatabaseKey(); !ok {
		return &ValidationError{Name: "protectedDatabaseKey", err: errors.New(`ent: missing required field "User.protectedDatabaseKey"`)}
	}
	if v, ok := uc.mutation.ProtectedDatabaseKey(); ok {
		if err := user.ProtectedDatabaseKeyValidator(v); err != nil {
			return &ValidationError{Name: "protectedDatabaseKey", err: fmt.Errorf(`ent: validator failed for field "User.protectedDatabaseKey": %w`, err)}
		}
	}
	if _, ok := uc.mutation.ProtectedDatabaseKeyIv(); !ok {
		return &ValidationError{Name: "protectedDatabaseKeyIv", err: errors.New(`ent: missing required field "User.protectedDatabaseKeyIv"`)}
	}
	if v, ok := uc.mutation.ProtectedDatabaseKeyIv(); ok {
		if err := user.ProtectedDatabaseKeyIvValidator(v); err != nil {
			return &ValidationError{Name: "protectedDatabaseKeyIv", err: fmt.Errorf(`ent: validator failed for field "User.protectedDatabaseKeyIv": %w`, err)}
		}
	}
	if _, ok := uc.mutation.WebauthnEnabled(); !ok {
		return &ValidationError{Name: "webauthnEnabled", err: errors.New(`ent: missing required field "User.webauthnEnabled"`)}
	}
	if _, ok := uc.mutation.TotpEnabled(); !ok {
		return &ValidationError{Name: "totpEnabled", err: errors.New(`ent: missing required field "User.totpEnabled"`)}
	}
	if _, ok := uc.mutation.Verified(); !ok {
		return &ValidationError{Name: "verified", err: errors.New(`ent: missing required field "User.verified"`)}
	}
	return nil
}

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

func (uc *UserCreate) createSpec() (*User, *sqlgraph.CreateSpec) {
	var (
		_node = &User{config: uc.config}
		_spec = sqlgraph.NewCreateSpec(user.Table, sqlgraph.NewFieldSpec(user.FieldID, field.TypeUUID))
	)
	if id, ok := uc.mutation.ID(); ok {
		_node.ID = id
		_spec.ID.Value = &id
	}
	if value, ok := uc.mutation.Email(); ok {
		_spec.SetField(user.FieldEmail, field.TypeString, value)
		_node.Email = value
	}
	if value, ok := uc.mutation.StrengthenedMasterHash(); ok {
		_spec.SetField(user.FieldStrengthenedMasterHash, field.TypeBytes, value)
		_node.StrengthenedMasterHash = value
	}
	if value, ok := uc.mutation.StrengthenedMasterHashSalt(); ok {
		_spec.SetField(user.FieldStrengthenedMasterHashSalt, field.TypeBytes, value)
		_node.StrengthenedMasterHashSalt = value
	}
	if value, ok := uc.mutation.ProtectedDatabaseKey(); ok {
		_spec.SetField(user.FieldProtectedDatabaseKey, field.TypeBytes, value)
		_node.ProtectedDatabaseKey = value
	}
	if value, ok := uc.mutation.ProtectedDatabaseKeyIv(); ok {
		_spec.SetField(user.FieldProtectedDatabaseKeyIv, field.TypeBytes, value)
		_node.ProtectedDatabaseKeyIv = value
	}
	if value, ok := uc.mutation.WebauthnEnabled(); ok {
		_spec.SetField(user.FieldWebauthnEnabled, field.TypeBool, value)
		_node.WebauthnEnabled = value
	}
	if value, ok := uc.mutation.TotpEnabled(); ok {
		_spec.SetField(user.FieldTotpEnabled, field.TypeBool, value)
		_node.TotpEnabled = value
	}
	if value, ok := uc.mutation.Verified(); ok {
		_spec.SetField(user.FieldVerified, field.TypeBool, value)
		_node.Verified = value
	}
	if nodes := uc.mutation.TotpCredentialIDs(); len(nodes) > 0 {
		edge := &sqlgraph.EdgeSpec{
			Rel:     sqlgraph.O2O,
			Inverse: false,
			Table:   user.TotpCredentialTable,
			Columns: []string{user.TotpCredentialColumn},
			Bidi:    false,
			Target: &sqlgraph.EdgeTarget{
				IDSpec: sqlgraph.NewFieldSpec(totpcredential.FieldID, field.TypeUUID),
			},
		}
		for _, k := range nodes {
			edge.Target.Nodes = append(edge.Target.Nodes, k)
		}
		_spec.Edges = append(_spec.Edges, edge)
	}
	if nodes := uc.mutation.WebauthnCredentialsIDs(); len(nodes) > 0 {
		edge := &sqlgraph.EdgeSpec{
			Rel:     sqlgraph.O2M,
			Inverse: false,
			Table:   user.WebauthnCredentialsTable,
			Columns: []string{user.WebauthnCredentialsColumn},
			Bidi:    false,
			Target: &sqlgraph.EdgeTarget{
				IDSpec: sqlgraph.NewFieldSpec(webauthncredential.FieldID, field.TypeUUID),
			},
		}
		for _, k := range nodes {
			edge.Target.Nodes = append(edge.Target.Nodes, k)
		}
		_spec.Edges = append(_spec.Edges, edge)
	}
	if nodes := uc.mutation.WebauthnRegisterChallengesIDs(); len(nodes) > 0 {
		edge := &sqlgraph.EdgeSpec{
			Rel:     sqlgraph.O2M,
			Inverse: false,
			Table:   user.WebauthnRegisterChallengesTable,
			Columns: []string{user.WebauthnRegisterChallengesColumn},
			Bidi:    false,
			Target: &sqlgraph.EdgeTarget{
				IDSpec: sqlgraph.NewFieldSpec(webauthnregisterchallenge.FieldID, field.TypeUUID),
			},
		}
		for _, k := range nodes {
			edge.Target.Nodes = append(edge.Target.Nodes, k)
		}
		_spec.Edges = append(_spec.Edges, edge)
	}
	if nodes := uc.mutation.VaultsIDs(); len(nodes) > 0 {
		edge := &sqlgraph.EdgeSpec{
			Rel:     sqlgraph.O2M,
			Inverse: false,
			Table:   user.VaultsTable,
			Columns: []string{user.VaultsColumn},
			Bidi:    false,
			Target: &sqlgraph.EdgeTarget{
				IDSpec: sqlgraph.NewFieldSpec(vault.FieldID, field.TypeUUID),
			},
		}
		for _, k := range nodes {
			edge.Target.Nodes = append(edge.Target.Nodes, k)
		}
		_spec.Edges = append(_spec.Edges, edge)
	}
	if nodes := uc.mutation.SessionsIDs(); len(nodes) > 0 {
		edge := &sqlgraph.EdgeSpec{
			Rel:     sqlgraph.O2M,
			Inverse: false,
			Table:   user.SessionsTable,
			Columns: []string{user.SessionsColumn},
			Bidi:    false,
			Target: &sqlgraph.EdgeTarget{
				IDSpec: sqlgraph.NewFieldSpec(session.FieldID, field.TypeUUID),
			},
		}
		for _, k := range nodes {
			edge.Target.Nodes = append(edge.Target.Nodes, k)
		}
		_spec.Edges = append(_spec.Edges, edge)
	}
	if nodes := uc.mutation.ChallengesIDs(); len(nodes) > 0 {
		edge := &sqlgraph.EdgeSpec{
			Rel:     sqlgraph.O2M,
			Inverse: false,
			Table:   user.ChallengesTable,
			Columns: []string{user.ChallengesColumn},
			Bidi:    false,
			Target: &sqlgraph.EdgeTarget{
				IDSpec: sqlgraph.NewFieldSpec(challenge.FieldID, field.TypeUUID),
			},
		}
		for _, k := range nodes {
			edge.Target.Nodes = append(edge.Target.Nodes, k)
		}
		_spec.Edges = append(_spec.Edges, edge)
	}
	return _node, _spec
}

// UserCreateBulk is the builder for creating many User entities in bulk.
type UserCreateBulk struct {
	config
	builders []*UserCreate
}

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

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

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

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