// 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/AvengeMedia/dankcalendar/core/ent/account"
	"github.com/AvengeMedia/dankcalendar/core/ent/secret"
)

// SecretCreate is the builder for creating a Secret entity.
type SecretCreate struct {
	config
	mutation *SecretMutation
	hooks    []Hook
	conflict []sql.ConflictOption
}

// SetKey sets the "key" field.
func (_c *SecretCreate) SetKey(v string) *SecretCreate {
	_c.mutation.SetKey(v)
	return _c
}

// SetValue sets the "value" field.
func (_c *SecretCreate) SetValue(v []byte) *SecretCreate {
	_c.mutation.SetValue(v)
	return _c
}

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

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

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

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

// SetID sets the "id" field.
func (_c *SecretCreate) SetID(v string) *SecretCreate {
	_c.mutation.SetID(v)
	return _c
}

// SetAccountID sets the "account" edge to the Account entity by ID.
func (_c *SecretCreate) SetAccountID(id string) *SecretCreate {
	_c.mutation.SetAccountID(id)
	return _c
}

// SetAccount sets the "account" edge to the Account entity.
func (_c *SecretCreate) SetAccount(v *Account) *SecretCreate {
	return _c.SetAccountID(v.ID)
}

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

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

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

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

// ExecX is like Exec, but panics if an error occurs.
func (_c *SecretCreate) 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 *SecretCreate) defaults() {
	if _, ok := _c.mutation.CreatedAt(); !ok {
		v := secret.DefaultCreatedAt()
		_c.mutation.SetCreatedAt(v)
	}
	if _, ok := _c.mutation.UpdatedAt(); !ok {
		v := secret.DefaultUpdatedAt()
		_c.mutation.SetUpdatedAt(v)
	}
}

// check runs all checks and user-defined validators on the builder.
func (_c *SecretCreate) check() error {
	if _, ok := _c.mutation.Key(); !ok {
		return &ValidationError{Name: "key", err: errors.New(`ent: missing required field "Secret.key"`)}
	}
	if v, ok := _c.mutation.Key(); ok {
		if err := secret.KeyValidator(v); err != nil {
			return &ValidationError{Name: "key", err: fmt.Errorf(`ent: validator failed for field "Secret.key": %w`, err)}
		}
	}
	if _, ok := _c.mutation.Value(); !ok {
		return &ValidationError{Name: "value", err: errors.New(`ent: missing required field "Secret.value"`)}
	}
	if _, ok := _c.mutation.CreatedAt(); !ok {
		return &ValidationError{Name: "created_at", err: errors.New(`ent: missing required field "Secret.created_at"`)}
	}
	if _, ok := _c.mutation.UpdatedAt(); !ok {
		return &ValidationError{Name: "updated_at", err: errors.New(`ent: missing required field "Secret.updated_at"`)}
	}
	if v, ok := _c.mutation.ID(); ok {
		if err := secret.IDValidator(v); err != nil {
			return &ValidationError{Name: "id", err: fmt.Errorf(`ent: validator failed for field "Secret.id": %w`, err)}
		}
	}
	if len(_c.mutation.AccountIDs()) == 0 {
		return &ValidationError{Name: "account", err: errors.New(`ent: missing required edge "Secret.account"`)}
	}
	return nil
}

func (_c *SecretCreate) sqlSave(ctx context.Context) (*Secret, 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.(string); ok {
			_node.ID = id
		} else {
			return nil, fmt.Errorf("unexpected Secret.ID type: %T", _spec.ID.Value)
		}
	}
	_c.mutation.id = &_node.ID
	_c.mutation.done = true
	return _node, nil
}

func (_c *SecretCreate) createSpec() (*Secret, *sqlgraph.CreateSpec) {
	var (
		_node = &Secret{config: _c.config}
		_spec = sqlgraph.NewCreateSpec(secret.Table, sqlgraph.NewFieldSpec(secret.FieldID, field.TypeString))
	)
	_spec.OnConflict = _c.conflict
	if id, ok := _c.mutation.ID(); ok {
		_node.ID = id
		_spec.ID.Value = id
	}
	if value, ok := _c.mutation.Key(); ok {
		_spec.SetField(secret.FieldKey, field.TypeString, value)
		_node.Key = value
	}
	if value, ok := _c.mutation.Value(); ok {
		_spec.SetField(secret.FieldValue, field.TypeBytes, value)
		_node.Value = value
	}
	if value, ok := _c.mutation.CreatedAt(); ok {
		_spec.SetField(secret.FieldCreatedAt, field.TypeTime, value)
		_node.CreatedAt = value
	}
	if value, ok := _c.mutation.UpdatedAt(); ok {
		_spec.SetField(secret.FieldUpdatedAt, field.TypeTime, value)
		_node.UpdatedAt = value
	}
	if nodes := _c.mutation.AccountIDs(); len(nodes) > 0 {
		edge := &sqlgraph.EdgeSpec{
			Rel:     sqlgraph.M2O,
			Inverse: true,
			Table:   secret.AccountTable,
			Columns: []string{secret.AccountColumn},
			Bidi:    false,
			Target: &sqlgraph.EdgeTarget{
				IDSpec: sqlgraph.NewFieldSpec(account.FieldID, field.TypeString),
			},
		}
		for _, k := range nodes {
			edge.Target.Nodes = append(edge.Target.Nodes, k)
		}
		_node.account_secrets = &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.Secret.Create().
//		SetKey(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.SecretUpsert) {
//			SetKey(v+v).
//		}).
//		Exec(ctx)
func (_c *SecretCreate) OnConflict(opts ...sql.ConflictOption) *SecretUpsertOne {
	_c.conflict = opts
	return &SecretUpsertOne{
		create: _c,
	}
}

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

type (
	// SecretUpsertOne is the builder for "upsert"-ing
	//  one Secret node.
	SecretUpsertOne struct {
		create *SecretCreate
	}

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

// SetKey sets the "key" field.
func (u *SecretUpsert) SetKey(v string) *SecretUpsert {
	u.Set(secret.FieldKey, v)
	return u
}

// UpdateKey sets the "key" field to the value that was provided on create.
func (u *SecretUpsert) UpdateKey() *SecretUpsert {
	u.SetExcluded(secret.FieldKey)
	return u
}

// SetValue sets the "value" field.
func (u *SecretUpsert) SetValue(v []byte) *SecretUpsert {
	u.Set(secret.FieldValue, v)
	return u
}

// UpdateValue sets the "value" field to the value that was provided on create.
func (u *SecretUpsert) UpdateValue() *SecretUpsert {
	u.SetExcluded(secret.FieldValue)
	return u
}

// SetUpdatedAt sets the "updated_at" field.
func (u *SecretUpsert) SetUpdatedAt(v time.Time) *SecretUpsert {
	u.Set(secret.FieldUpdatedAt, v)
	return u
}

// UpdateUpdatedAt sets the "updated_at" field to the value that was provided on create.
func (u *SecretUpsert) UpdateUpdatedAt() *SecretUpsert {
	u.SetExcluded(secret.FieldUpdatedAt)
	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.Secret.Create().
//		OnConflict(
//			sql.ResolveWithNewValues(),
//			sql.ResolveWith(func(u *sql.UpdateSet) {
//				u.SetIgnore(secret.FieldID)
//			}),
//		).
//		Exec(ctx)
func (u *SecretUpsertOne) UpdateNewValues() *SecretUpsertOne {
	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(secret.FieldID)
		}
		if _, exists := u.create.mutation.CreatedAt(); exists {
			s.SetIgnore(secret.FieldCreatedAt)
		}
	}))
	return u
}

// Ignore sets each column to itself in case of conflict.
// Using this option is equivalent to using:
//
//	client.Secret.Create().
//	    OnConflict(sql.ResolveWithIgnore()).
//	    Exec(ctx)
func (u *SecretUpsertOne) Ignore() *SecretUpsertOne {
	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 *SecretUpsertOne) DoNothing() *SecretUpsertOne {
	u.create.conflict = append(u.create.conflict, sql.DoNothing())
	return u
}

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

// SetKey sets the "key" field.
func (u *SecretUpsertOne) SetKey(v string) *SecretUpsertOne {
	return u.Update(func(s *SecretUpsert) {
		s.SetKey(v)
	})
}

// UpdateKey sets the "key" field to the value that was provided on create.
func (u *SecretUpsertOne) UpdateKey() *SecretUpsertOne {
	return u.Update(func(s *SecretUpsert) {
		s.UpdateKey()
	})
}

// SetValue sets the "value" field.
func (u *SecretUpsertOne) SetValue(v []byte) *SecretUpsertOne {
	return u.Update(func(s *SecretUpsert) {
		s.SetValue(v)
	})
}

// UpdateValue sets the "value" field to the value that was provided on create.
func (u *SecretUpsertOne) UpdateValue() *SecretUpsertOne {
	return u.Update(func(s *SecretUpsert) {
		s.UpdateValue()
	})
}

// SetUpdatedAt sets the "updated_at" field.
func (u *SecretUpsertOne) SetUpdatedAt(v time.Time) *SecretUpsertOne {
	return u.Update(func(s *SecretUpsert) {
		s.SetUpdatedAt(v)
	})
}

// UpdateUpdatedAt sets the "updated_at" field to the value that was provided on create.
func (u *SecretUpsertOne) UpdateUpdatedAt() *SecretUpsertOne {
	return u.Update(func(s *SecretUpsert) {
		s.UpdateUpdatedAt()
	})
}

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

// ExecX is like Exec, but panics if an error occurs.
func (u *SecretUpsertOne) 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 *SecretUpsertOne) ID(ctx context.Context) (id string, 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: SecretUpsertOne.ID is not supported by MySQL driver. Use SecretUpsertOne.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 *SecretUpsertOne) IDX(ctx context.Context) string {
	id, err := u.ID(ctx)
	if err != nil {
		panic(err)
	}
	return id
}

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

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

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

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

// OnConflict allows configuring the `ON CONFLICT` / `ON DUPLICATE KEY` clause
// of the `INSERT` statement. For example:
//
//	client.Secret.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.SecretUpsert) {
//			SetKey(v+v).
//		}).
//		Exec(ctx)
func (_c *SecretCreateBulk) OnConflict(opts ...sql.ConflictOption) *SecretUpsertBulk {
	_c.conflict = opts
	return &SecretUpsertBulk{
		create: _c,
	}
}

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

// SecretUpsertBulk is the builder for "upsert"-ing
// a bulk of Secret nodes.
type SecretUpsertBulk struct {
	create *SecretCreateBulk
}

// UpdateNewValues updates the mutable fields using the new values that
// were set on create. Using this option is equivalent to using:
//
//	client.Secret.Create().
//		OnConflict(
//			sql.ResolveWithNewValues(),
//			sql.ResolveWith(func(u *sql.UpdateSet) {
//				u.SetIgnore(secret.FieldID)
//			}),
//		).
//		Exec(ctx)
func (u *SecretUpsertBulk) UpdateNewValues() *SecretUpsertBulk {
	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(secret.FieldID)
			}
			if _, exists := b.mutation.CreatedAt(); exists {
				s.SetIgnore(secret.FieldCreatedAt)
			}
		}
	}))
	return u
}

// Ignore sets each column to itself in case of conflict.
// Using this option is equivalent to using:
//
//	client.Secret.Create().
//		OnConflict(sql.ResolveWithIgnore()).
//		Exec(ctx)
func (u *SecretUpsertBulk) Ignore() *SecretUpsertBulk {
	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 *SecretUpsertBulk) DoNothing() *SecretUpsertBulk {
	u.create.conflict = append(u.create.conflict, sql.DoNothing())
	return u
}

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

// SetKey sets the "key" field.
func (u *SecretUpsertBulk) SetKey(v string) *SecretUpsertBulk {
	return u.Update(func(s *SecretUpsert) {
		s.SetKey(v)
	})
}

// UpdateKey sets the "key" field to the value that was provided on create.
func (u *SecretUpsertBulk) UpdateKey() *SecretUpsertBulk {
	return u.Update(func(s *SecretUpsert) {
		s.UpdateKey()
	})
}

// SetValue sets the "value" field.
func (u *SecretUpsertBulk) SetValue(v []byte) *SecretUpsertBulk {
	return u.Update(func(s *SecretUpsert) {
		s.SetValue(v)
	})
}

// UpdateValue sets the "value" field to the value that was provided on create.
func (u *SecretUpsertBulk) UpdateValue() *SecretUpsertBulk {
	return u.Update(func(s *SecretUpsert) {
		s.UpdateValue()
	})
}

// SetUpdatedAt sets the "updated_at" field.
func (u *SecretUpsertBulk) SetUpdatedAt(v time.Time) *SecretUpsertBulk {
	return u.Update(func(s *SecretUpsert) {
		s.SetUpdatedAt(v)
	})
}

// UpdateUpdatedAt sets the "updated_at" field to the value that was provided on create.
func (u *SecretUpsertBulk) UpdateUpdatedAt() *SecretUpsertBulk {
	return u.Update(func(s *SecretUpsert) {
		s.UpdateUpdatedAt()
	})
}

// Exec executes the query.
func (u *SecretUpsertBulk) 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 SecretCreateBulk instead", i)
		}
	}
	if len(u.create.conflict) == 0 {
		return errors.New("ent: missing options for SecretCreateBulk.OnConflict")
	}
	return u.create.Exec(ctx)
}

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