// Code generated by ent, DO NOT EDIT.

package ent

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

	"entgo.io/ent/dialect/sql"
	"entgo.io/ent/dialect/sql/sqlgraph"
	"entgo.io/ent/schema/field"
	"github.com/crowdsecurity/crowdsec/pkg/database/ent/configitem"
)

// ConfigItemCreate is the builder for creating a ConfigItem entity.
type ConfigItemCreate struct {
	config
	mutation *ConfigItemMutation
	hooks    []Hook
	conflict []sql.ConflictOption
}

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

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

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

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

// SetName sets the "name" field.
func (_c *ConfigItemCreate) SetName(v string) *ConfigItemCreate {
	_c.mutation.SetName(v)
	return _c
}

// SetValue sets the "value" field.
func (_c *ConfigItemCreate) SetValue(v string) *ConfigItemCreate {
	_c.mutation.SetValue(v)
	return _c
}

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

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

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

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

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

// check runs all checks and user-defined validators on the builder.
func (_c *ConfigItemCreate) check() error {
	if _, ok := _c.mutation.CreatedAt(); !ok {
		return &ValidationError{Name: "created_at", err: errors.New(`ent: missing required field "ConfigItem.created_at"`)}
	}
	if _, ok := _c.mutation.UpdatedAt(); !ok {
		return &ValidationError{Name: "updated_at", err: errors.New(`ent: missing required field "ConfigItem.updated_at"`)}
	}
	if _, ok := _c.mutation.Name(); !ok {
		return &ValidationError{Name: "name", err: errors.New(`ent: missing required field "ConfigItem.name"`)}
	}
	if _, ok := _c.mutation.Value(); !ok {
		return &ValidationError{Name: "value", err: errors.New(`ent: missing required field "ConfigItem.value"`)}
	}
	return nil
}

func (_c *ConfigItemCreate) sqlSave(ctx context.Context) (*ConfigItem, 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
	}
	id := _spec.ID.Value.(int64)
	_node.ID = int(id)
	_c.mutation.id = &_node.ID
	_c.mutation.done = true
	return _node, nil
}

func (_c *ConfigItemCreate) createSpec() (*ConfigItem, *sqlgraph.CreateSpec) {
	var (
		_node = &ConfigItem{config: _c.config}
		_spec = sqlgraph.NewCreateSpec(configitem.Table, sqlgraph.NewFieldSpec(configitem.FieldID, field.TypeInt))
	)
	_spec.OnConflict = _c.conflict
	if value, ok := _c.mutation.CreatedAt(); ok {
		_spec.SetField(configitem.FieldCreatedAt, field.TypeTime, value)
		_node.CreatedAt = value
	}
	if value, ok := _c.mutation.UpdatedAt(); ok {
		_spec.SetField(configitem.FieldUpdatedAt, field.TypeTime, value)
		_node.UpdatedAt = value
	}
	if value, ok := _c.mutation.Name(); ok {
		_spec.SetField(configitem.FieldName, field.TypeString, value)
		_node.Name = value
	}
	if value, ok := _c.mutation.Value(); ok {
		_spec.SetField(configitem.FieldValue, field.TypeString, value)
		_node.Value = value
	}
	return _node, _spec
}

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

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

type (
	// ConfigItemUpsertOne is the builder for "upsert"-ing
	//  one ConfigItem node.
	ConfigItemUpsertOne struct {
		create *ConfigItemCreate
	}

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

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

// UpdateUpdatedAt sets the "updated_at" field to the value that was provided on create.
func (u *ConfigItemUpsert) UpdateUpdatedAt() *ConfigItemUpsert {
	u.SetExcluded(configitem.FieldUpdatedAt)
	return u
}

// SetValue sets the "value" field.
func (u *ConfigItemUpsert) SetValue(v string) *ConfigItemUpsert {
	u.Set(configitem.FieldValue, v)
	return u
}

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

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

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

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

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

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

// SetValue sets the "value" field.
func (u *ConfigItemUpsertOne) SetValue(v string) *ConfigItemUpsertOne {
	return u.Update(func(s *ConfigItemUpsert) {
		s.SetValue(v)
	})
}

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

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

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

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

// Save creates the ConfigItem entities in the database.
func (_c *ConfigItemCreateBulk) Save(ctx context.Context) ([]*ConfigItem, error) {
	if _c.err != nil {
		return nil, _c.err
	}
	specs := make([]*sqlgraph.CreateSpec, len(_c.builders))
	nodes := make([]*ConfigItem, 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.(*ConfigItemMutation)
				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
				if specs[i].ID.Value != nil {
					id := specs[i].ID.Value.(int64)
					nodes[i].ID = int(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 *ConfigItemCreateBulk) SaveX(ctx context.Context) []*ConfigItem {
	v, err := _c.Save(ctx)
	if err != nil {
		panic(err)
	}
	return v
}

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

// ExecX is like Exec, but panics if an error occurs.
func (_c *ConfigItemCreateBulk) 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.ConfigItem.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.ConfigItemUpsert) {
//			SetCreatedAt(v+v).
//		}).
//		Exec(ctx)
func (_c *ConfigItemCreateBulk) OnConflict(opts ...sql.ConflictOption) *ConfigItemUpsertBulk {
	_c.conflict = opts
	return &ConfigItemUpsertBulk{
		create: _c,
	}
}

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

// ConfigItemUpsertBulk is the builder for "upsert"-ing
// a bulk of ConfigItem nodes.
type ConfigItemUpsertBulk struct {
	create *ConfigItemCreateBulk
}

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

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

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

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

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

// SetValue sets the "value" field.
func (u *ConfigItemUpsertBulk) SetValue(v string) *ConfigItemUpsertBulk {
	return u.Update(func(s *ConfigItemUpsert) {
		s.SetValue(v)
	})
}

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

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

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