// Code generated by ent, DO NOT EDIT.

package ent

import (
	"context"
	"errors"
	"fmt"
	"time"

	"entgo.io/ent/dialect"
	"entgo.io/ent/dialect/sql"
	"entgo.io/ent/dialect/sql/sqlgraph"
	"entgo.io/ent/schema/field"
	"github.com/google/uuid"
	"github.com/lightsparkdev/spark/so/ent/entitydkgkey"
	"github.com/lightsparkdev/spark/so/ent/signingkeyshare"
)

// EntityDkgKeyCreate is the builder for creating a EntityDkgKey entity.
type EntityDkgKeyCreate struct {
	config
	mutation *EntityDkgKeyMutation
	hooks    []Hook
	conflict []sql.ConflictOption
}

// SetCreateTime sets the "create_time" field.
func (edkc *EntityDkgKeyCreate) SetCreateTime(t time.Time) *EntityDkgKeyCreate {
	edkc.mutation.SetCreateTime(t)
	return edkc
}

// SetNillableCreateTime sets the "create_time" field if the given value is not nil.
func (edkc *EntityDkgKeyCreate) SetNillableCreateTime(t *time.Time) *EntityDkgKeyCreate {
	if t != nil {
		edkc.SetCreateTime(*t)
	}
	return edkc
}

// SetUpdateTime sets the "update_time" field.
func (edkc *EntityDkgKeyCreate) SetUpdateTime(t time.Time) *EntityDkgKeyCreate {
	edkc.mutation.SetUpdateTime(t)
	return edkc
}

// SetNillableUpdateTime sets the "update_time" field if the given value is not nil.
func (edkc *EntityDkgKeyCreate) SetNillableUpdateTime(t *time.Time) *EntityDkgKeyCreate {
	if t != nil {
		edkc.SetUpdateTime(*t)
	}
	return edkc
}

// SetKeyType sets the "key_type" field.
func (edkc *EntityDkgKeyCreate) SetKeyType(s string) *EntityDkgKeyCreate {
	edkc.mutation.SetKeyType(s)
	return edkc
}

// SetNillableKeyType sets the "key_type" field if the given value is not nil.
func (edkc *EntityDkgKeyCreate) SetNillableKeyType(s *string) *EntityDkgKeyCreate {
	if s != nil {
		edkc.SetKeyType(*s)
	}
	return edkc
}

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

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

// SetSigningKeyshareID sets the "signing_keyshare" edge to the SigningKeyshare entity by ID.
func (edkc *EntityDkgKeyCreate) SetSigningKeyshareID(id uuid.UUID) *EntityDkgKeyCreate {
	edkc.mutation.SetSigningKeyshareID(id)
	return edkc
}

// SetSigningKeyshare sets the "signing_keyshare" edge to the SigningKeyshare entity.
func (edkc *EntityDkgKeyCreate) SetSigningKeyshare(s *SigningKeyshare) *EntityDkgKeyCreate {
	return edkc.SetSigningKeyshareID(s.ID)
}

// Mutation returns the EntityDkgKeyMutation object of the builder.
func (edkc *EntityDkgKeyCreate) Mutation() *EntityDkgKeyMutation {
	return edkc.mutation
}

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

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

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

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

// defaults sets the default values of the builder before save.
func (edkc *EntityDkgKeyCreate) defaults() {
	if _, ok := edkc.mutation.CreateTime(); !ok {
		v := entitydkgkey.DefaultCreateTime()
		edkc.mutation.SetCreateTime(v)
	}
	if _, ok := edkc.mutation.UpdateTime(); !ok {
		v := entitydkgkey.DefaultUpdateTime()
		edkc.mutation.SetUpdateTime(v)
	}
	if _, ok := edkc.mutation.KeyType(); !ok {
		v := entitydkgkey.DefaultKeyType
		edkc.mutation.SetKeyType(v)
	}
	if _, ok := edkc.mutation.ID(); !ok {
		v := entitydkgkey.DefaultID()
		edkc.mutation.SetID(v)
	}
}

// check runs all checks and user-defined validators on the builder.
func (edkc *EntityDkgKeyCreate) check() error {
	if _, ok := edkc.mutation.CreateTime(); !ok {
		return &ValidationError{Name: "create_time", err: errors.New(`ent: missing required field "EntityDkgKey.create_time"`)}
	}
	if _, ok := edkc.mutation.UpdateTime(); !ok {
		return &ValidationError{Name: "update_time", err: errors.New(`ent: missing required field "EntityDkgKey.update_time"`)}
	}
	if _, ok := edkc.mutation.KeyType(); !ok {
		return &ValidationError{Name: "key_type", err: errors.New(`ent: missing required field "EntityDkgKey.key_type"`)}
	}
	if len(edkc.mutation.SigningKeyshareIDs()) == 0 {
		return &ValidationError{Name: "signing_keyshare", err: errors.New(`ent: missing required edge "EntityDkgKey.signing_keyshare"`)}
	}
	return nil
}

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

func (edkc *EntityDkgKeyCreate) createSpec() (*EntityDkgKey, *sqlgraph.CreateSpec) {
	var (
		_node = &EntityDkgKey{config: edkc.config}
		_spec = sqlgraph.NewCreateSpec(entitydkgkey.Table, sqlgraph.NewFieldSpec(entitydkgkey.FieldID, field.TypeUUID))
	)
	_spec.OnConflict = edkc.conflict
	if id, ok := edkc.mutation.ID(); ok {
		_node.ID = id
		_spec.ID.Value = &id
	}
	if value, ok := edkc.mutation.CreateTime(); ok {
		_spec.SetField(entitydkgkey.FieldCreateTime, field.TypeTime, value)
		_node.CreateTime = value
	}
	if value, ok := edkc.mutation.UpdateTime(); ok {
		_spec.SetField(entitydkgkey.FieldUpdateTime, field.TypeTime, value)
		_node.UpdateTime = value
	}
	if value, ok := edkc.mutation.KeyType(); ok {
		_spec.SetField(entitydkgkey.FieldKeyType, field.TypeString, value)
		_node.KeyType = value
	}
	if nodes := edkc.mutation.SigningKeyshareIDs(); len(nodes) > 0 {
		edge := &sqlgraph.EdgeSpec{
			Rel:     sqlgraph.M2O,
			Inverse: false,
			Table:   entitydkgkey.SigningKeyshareTable,
			Columns: []string{entitydkgkey.SigningKeyshareColumn},
			Bidi:    false,
			Target: &sqlgraph.EdgeTarget{
				IDSpec: sqlgraph.NewFieldSpec(signingkeyshare.FieldID, field.TypeUUID),
			},
		}
		for _, k := range nodes {
			edge.Target.Nodes = append(edge.Target.Nodes, k)
		}
		_node.entity_dkg_key_signing_keyshare = &nodes[0]
		_spec.Edges = append(_spec.Edges, edge)
	}
	return _node, _spec
}

// OnConflict allows configuring the `ON CONFLICT` / `ON DUPLICATE KEY` clause
// of the `INSERT` statement. For example:
//
//	client.EntityDkgKey.Create().
//		SetCreateTime(v).
//		OnConflict(
//			// Update the row with the new values
//			// the was proposed for insertion.
//			sql.ResolveWithNewValues(),
//		).
//		// Override some of the fields with custom
//		// update values.
//		Update(func(u *ent.EntityDkgKeyUpsert) {
//			SetCreateTime(v+v).
//		}).
//		Exec(ctx)
func (edkc *EntityDkgKeyCreate) OnConflict(opts ...sql.ConflictOption) *EntityDkgKeyUpsertOne {
	edkc.conflict = opts
	return &EntityDkgKeyUpsertOne{
		create: edkc,
	}
}

// OnConflictColumns calls `OnConflict` and configures the columns
// as conflict target. Using this option is equivalent to using:
//
//	client.EntityDkgKey.Create().
//		OnConflict(sql.ConflictColumns(columns...)).
//		Exec(ctx)
func (edkc *EntityDkgKeyCreate) OnConflictColumns(columns ...string) *EntityDkgKeyUpsertOne {
	edkc.conflict = append(edkc.conflict, sql.ConflictColumns(columns...))
	return &EntityDkgKeyUpsertOne{
		create: edkc,
	}
}

type (
	// EntityDkgKeyUpsertOne is the builder for "upsert"-ing
	//  one EntityDkgKey node.
	EntityDkgKeyUpsertOne struct {
		create *EntityDkgKeyCreate
	}

	// EntityDkgKeyUpsert is the "OnConflict" setter.
	EntityDkgKeyUpsert struct {
		*sql.UpdateSet
	}
)

// SetUpdateTime sets the "update_time" field.
func (u *EntityDkgKeyUpsert) SetUpdateTime(v time.Time) *EntityDkgKeyUpsert {
	u.Set(entitydkgkey.FieldUpdateTime, v)
	return u
}

// UpdateUpdateTime sets the "update_time" field to the value that was provided on create.
func (u *EntityDkgKeyUpsert) UpdateUpdateTime() *EntityDkgKeyUpsert {
	u.SetExcluded(entitydkgkey.FieldUpdateTime)
	return u
}

// UpdateNewValues updates the mutable fields using the new values that were set on create except the ID field.
// Using this option is equivalent to using:
//
//	client.EntityDkgKey.Create().
//		OnConflict(
//			sql.ResolveWithNewValues(),
//			sql.ResolveWith(func(u *sql.UpdateSet) {
//				u.SetIgnore(entitydkgkey.FieldID)
//			}),
//		).
//		Exec(ctx)
func (u *EntityDkgKeyUpsertOne) UpdateNewValues() *EntityDkgKeyUpsertOne {
	u.create.conflict = append(u.create.conflict, sql.ResolveWithNewValues())
	u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(s *sql.UpdateSet) {
		if _, exists := u.create.mutation.ID(); exists {
			s.SetIgnore(entitydkgkey.FieldID)
		}
		if _, exists := u.create.mutation.CreateTime(); exists {
			s.SetIgnore(entitydkgkey.FieldCreateTime)
		}
		if _, exists := u.create.mutation.KeyType(); exists {
			s.SetIgnore(entitydkgkey.FieldKeyType)
		}
	}))
	return u
}

// Ignore sets each column to itself in case of conflict.
// Using this option is equivalent to using:
//
//	client.EntityDkgKey.Create().
//	    OnConflict(sql.ResolveWithIgnore()).
//	    Exec(ctx)
func (u *EntityDkgKeyUpsertOne) Ignore() *EntityDkgKeyUpsertOne {
	u.create.conflict = append(u.create.conflict, sql.ResolveWithIgnore())
	return u
}

// DoNothing configures the conflict_action to `DO NOTHING`.
// Supported only by SQLite and PostgreSQL.
func (u *EntityDkgKeyUpsertOne) DoNothing() *EntityDkgKeyUpsertOne {
	u.create.conflict = append(u.create.conflict, sql.DoNothing())
	return u
}

// Update allows overriding fields `UPDATE` values. See the EntityDkgKeyCreate.OnConflict
// documentation for more info.
func (u *EntityDkgKeyUpsertOne) Update(set func(*EntityDkgKeyUpsert)) *EntityDkgKeyUpsertOne {
	u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(update *sql.UpdateSet) {
		set(&EntityDkgKeyUpsert{UpdateSet: update})
	}))
	return u
}

// SetUpdateTime sets the "update_time" field.
func (u *EntityDkgKeyUpsertOne) SetUpdateTime(v time.Time) *EntityDkgKeyUpsertOne {
	return u.Update(func(s *EntityDkgKeyUpsert) {
		s.SetUpdateTime(v)
	})
}

// UpdateUpdateTime sets the "update_time" field to the value that was provided on create.
func (u *EntityDkgKeyUpsertOne) UpdateUpdateTime() *EntityDkgKeyUpsertOne {
	return u.Update(func(s *EntityDkgKeyUpsert) {
		s.UpdateUpdateTime()
	})
}

// Exec executes the query.
func (u *EntityDkgKeyUpsertOne) Exec(ctx context.Context) error {
	if len(u.create.conflict) == 0 {
		return errors.New("ent: missing options for EntityDkgKeyCreate.OnConflict")
	}
	return u.create.Exec(ctx)
}

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

// Exec executes the UPSERT query and returns the inserted/updated ID.
func (u *EntityDkgKeyUpsertOne) ID(ctx context.Context) (id uuid.UUID, err error) {
	if u.create.driver.Dialect() == dialect.MySQL {
		// In case of "ON CONFLICT", there is no way to get back non-numeric ID
		// fields from the database since MySQL does not support the RETURNING clause.
		return id, errors.New("ent: EntityDkgKeyUpsertOne.ID is not supported by MySQL driver. Use EntityDkgKeyUpsertOne.Exec instead")
	}
	node, err := u.create.Save(ctx)
	if err != nil {
		return id, err
	}
	return node.ID, nil
}

// IDX is like ID, but panics if an error occurs.
func (u *EntityDkgKeyUpsertOne) IDX(ctx context.Context) uuid.UUID {
	id, err := u.ID(ctx)
	if err != nil {
		panic(err)
	}
	return id
}

// EntityDkgKeyCreateBulk is the builder for creating many EntityDkgKey entities in bulk.
type EntityDkgKeyCreateBulk struct {
	config
	err      error
	builders []*EntityDkgKeyCreate
	conflict []sql.ConflictOption
}

// Save creates the EntityDkgKey entities in the database.
func (edkcb *EntityDkgKeyCreateBulk) Save(ctx context.Context) ([]*EntityDkgKey, error) {
	if edkcb.err != nil {
		return nil, edkcb.err
	}
	specs := make([]*sqlgraph.CreateSpec, len(edkcb.builders))
	nodes := make([]*EntityDkgKey, len(edkcb.builders))
	mutators := make([]Mutator, len(edkcb.builders))
	for i := range edkcb.builders {
		func(i int, root context.Context) {
			builder := edkcb.builders[i]
			builder.defaults()
			var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
				mutation, ok := m.(*EntityDkgKeyMutation)
				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, edkcb.builders[i+1].mutation)
				} else {
					spec := &sqlgraph.BatchCreateSpec{Nodes: specs}
					spec.OnConflict = edkcb.conflict
					// Invoke the actual operation on the latest mutation in the chain.
					if err = sqlgraph.BatchCreate(ctx, edkcb.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, edkcb.builders[0].mutation); err != nil {
			return nil, err
		}
	}
	return nodes, nil
}

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

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

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

// OnConflict allows configuring the `ON CONFLICT` / `ON DUPLICATE KEY` clause
// of the `INSERT` statement. For example:
//
//	client.EntityDkgKey.CreateBulk(builders...).
//		OnConflict(
//			// Update the row with the new values
//			// the was proposed for insertion.
//			sql.ResolveWithNewValues(),
//		).
//		// Override some of the fields with custom
//		// update values.
//		Update(func(u *ent.EntityDkgKeyUpsert) {
//			SetCreateTime(v+v).
//		}).
//		Exec(ctx)
func (edkcb *EntityDkgKeyCreateBulk) OnConflict(opts ...sql.ConflictOption) *EntityDkgKeyUpsertBulk {
	edkcb.conflict = opts
	return &EntityDkgKeyUpsertBulk{
		create: edkcb,
	}
}

// OnConflictColumns calls `OnConflict` and configures the columns
// as conflict target. Using this option is equivalent to using:
//
//	client.EntityDkgKey.Create().
//		OnConflict(sql.ConflictColumns(columns...)).
//		Exec(ctx)
func (edkcb *EntityDkgKeyCreateBulk) OnConflictColumns(columns ...string) *EntityDkgKeyUpsertBulk {
	edkcb.conflict = append(edkcb.conflict, sql.ConflictColumns(columns...))
	return &EntityDkgKeyUpsertBulk{
		create: edkcb,
	}
}

// EntityDkgKeyUpsertBulk is the builder for "upsert"-ing
// a bulk of EntityDkgKey nodes.
type EntityDkgKeyUpsertBulk struct {
	create *EntityDkgKeyCreateBulk
}

// UpdateNewValues updates the mutable fields using the new values that
// were set on create. Using this option is equivalent to using:
//
//	client.EntityDkgKey.Create().
//		OnConflict(
//			sql.ResolveWithNewValues(),
//			sql.ResolveWith(func(u *sql.UpdateSet) {
//				u.SetIgnore(entitydkgkey.FieldID)
//			}),
//		).
//		Exec(ctx)
func (u *EntityDkgKeyUpsertBulk) UpdateNewValues() *EntityDkgKeyUpsertBulk {
	u.create.conflict = append(u.create.conflict, sql.ResolveWithNewValues())
	u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(s *sql.UpdateSet) {
		for _, b := range u.create.builders {
			if _, exists := b.mutation.ID(); exists {
				s.SetIgnore(entitydkgkey.FieldID)
			}
			if _, exists := b.mutation.CreateTime(); exists {
				s.SetIgnore(entitydkgkey.FieldCreateTime)
			}
			if _, exists := b.mutation.KeyType(); exists {
				s.SetIgnore(entitydkgkey.FieldKeyType)
			}
		}
	}))
	return u
}

// Ignore sets each column to itself in case of conflict.
// Using this option is equivalent to using:
//
//	client.EntityDkgKey.Create().
//		OnConflict(sql.ResolveWithIgnore()).
//		Exec(ctx)
func (u *EntityDkgKeyUpsertBulk) Ignore() *EntityDkgKeyUpsertBulk {
	u.create.conflict = append(u.create.conflict, sql.ResolveWithIgnore())
	return u
}

// DoNothing configures the conflict_action to `DO NOTHING`.
// Supported only by SQLite and PostgreSQL.
func (u *EntityDkgKeyUpsertBulk) DoNothing() *EntityDkgKeyUpsertBulk {
	u.create.conflict = append(u.create.conflict, sql.DoNothing())
	return u
}

// Update allows overriding fields `UPDATE` values. See the EntityDkgKeyCreateBulk.OnConflict
// documentation for more info.
func (u *EntityDkgKeyUpsertBulk) Update(set func(*EntityDkgKeyUpsert)) *EntityDkgKeyUpsertBulk {
	u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(update *sql.UpdateSet) {
		set(&EntityDkgKeyUpsert{UpdateSet: update})
	}))
	return u
}

// SetUpdateTime sets the "update_time" field.
func (u *EntityDkgKeyUpsertBulk) SetUpdateTime(v time.Time) *EntityDkgKeyUpsertBulk {
	return u.Update(func(s *EntityDkgKeyUpsert) {
		s.SetUpdateTime(v)
	})
}

// UpdateUpdateTime sets the "update_time" field to the value that was provided on create.
func (u *EntityDkgKeyUpsertBulk) UpdateUpdateTime() *EntityDkgKeyUpsertBulk {
	return u.Update(func(s *EntityDkgKeyUpsert) {
		s.UpdateUpdateTime()
	})
}

// Exec executes the query.
func (u *EntityDkgKeyUpsertBulk) Exec(ctx context.Context) error {
	if u.create.err != nil {
		return u.create.err
	}
	for i, b := range u.create.builders {
		if len(b.conflict) != 0 {
			return fmt.Errorf("ent: OnConflict was set for builder %d. Set it on the EntityDkgKeyCreateBulk instead", i)
		}
	}
	if len(u.create.conflict) == 0 {
		return errors.New("ent: missing options for EntityDkgKeyCreateBulk.OnConflict")
	}
	return u.create.Exec(ctx)
}

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