// Code generated by ent, DO NOT EDIT.

package db

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/chaitin/MonkeyCode/backend/db/extension"
	"github.com/google/uuid"
)

// ExtensionCreate is the builder for creating a Extension entity.
type ExtensionCreate struct {
	config
	mutation *ExtensionMutation
	hooks    []Hook
	conflict []sql.ConflictOption
}

// SetVersion sets the "version" field.
func (ec *ExtensionCreate) SetVersion(s string) *ExtensionCreate {
	ec.mutation.SetVersion(s)
	return ec
}

// SetPath sets the "path" field.
func (ec *ExtensionCreate) SetPath(s string) *ExtensionCreate {
	ec.mutation.SetPath(s)
	return ec
}

// SetCreatedAt sets the "created_at" field.
func (ec *ExtensionCreate) SetCreatedAt(t time.Time) *ExtensionCreate {
	ec.mutation.SetCreatedAt(t)
	return ec
}

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

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

// Mutation returns the ExtensionMutation object of the builder.
func (ec *ExtensionCreate) Mutation() *ExtensionMutation {
	return ec.mutation
}

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

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

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

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

// defaults sets the default values of the builder before save.
func (ec *ExtensionCreate) defaults() {
	if _, ok := ec.mutation.CreatedAt(); !ok {
		v := extension.DefaultCreatedAt()
		ec.mutation.SetCreatedAt(v)
	}
}

// check runs all checks and user-defined validators on the builder.
func (ec *ExtensionCreate) check() error {
	if _, ok := ec.mutation.Version(); !ok {
		return &ValidationError{Name: "version", err: errors.New(`db: missing required field "Extension.version"`)}
	}
	if _, ok := ec.mutation.Path(); !ok {
		return &ValidationError{Name: "path", err: errors.New(`db: missing required field "Extension.path"`)}
	}
	if _, ok := ec.mutation.CreatedAt(); !ok {
		return &ValidationError{Name: "created_at", err: errors.New(`db: missing required field "Extension.created_at"`)}
	}
	return nil
}

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

func (ec *ExtensionCreate) createSpec() (*Extension, *sqlgraph.CreateSpec) {
	var (
		_node = &Extension{config: ec.config}
		_spec = sqlgraph.NewCreateSpec(extension.Table, sqlgraph.NewFieldSpec(extension.FieldID, field.TypeUUID))
	)
	_spec.OnConflict = ec.conflict
	if id, ok := ec.mutation.ID(); ok {
		_node.ID = id
		_spec.ID.Value = &id
	}
	if value, ok := ec.mutation.Version(); ok {
		_spec.SetField(extension.FieldVersion, field.TypeString, value)
		_node.Version = value
	}
	if value, ok := ec.mutation.Path(); ok {
		_spec.SetField(extension.FieldPath, field.TypeString, value)
		_node.Path = value
	}
	if value, ok := ec.mutation.CreatedAt(); ok {
		_spec.SetField(extension.FieldCreatedAt, field.TypeTime, value)
		_node.CreatedAt = value
	}
	return _node, _spec
}

// OnConflict allows configuring the `ON CONFLICT` / `ON DUPLICATE KEY` clause
// of the `INSERT` statement. For example:
//
//	client.Extension.Create().
//		SetVersion(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.ExtensionUpsert) {
//			SetVersion(v+v).
//		}).
//		Exec(ctx)
func (ec *ExtensionCreate) OnConflict(opts ...sql.ConflictOption) *ExtensionUpsertOne {
	ec.conflict = opts
	return &ExtensionUpsertOne{
		create: ec,
	}
}

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

type (
	// ExtensionUpsertOne is the builder for "upsert"-ing
	//  one Extension node.
	ExtensionUpsertOne struct {
		create *ExtensionCreate
	}

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

// SetVersion sets the "version" field.
func (u *ExtensionUpsert) SetVersion(v string) *ExtensionUpsert {
	u.Set(extension.FieldVersion, v)
	return u
}

// UpdateVersion sets the "version" field to the value that was provided on create.
func (u *ExtensionUpsert) UpdateVersion() *ExtensionUpsert {
	u.SetExcluded(extension.FieldVersion)
	return u
}

// SetPath sets the "path" field.
func (u *ExtensionUpsert) SetPath(v string) *ExtensionUpsert {
	u.Set(extension.FieldPath, v)
	return u
}

// UpdatePath sets the "path" field to the value that was provided on create.
func (u *ExtensionUpsert) UpdatePath() *ExtensionUpsert {
	u.SetExcluded(extension.FieldPath)
	return u
}

// SetCreatedAt sets the "created_at" field.
func (u *ExtensionUpsert) SetCreatedAt(v time.Time) *ExtensionUpsert {
	u.Set(extension.FieldCreatedAt, v)
	return u
}

// UpdateCreatedAt sets the "created_at" field to the value that was provided on create.
func (u *ExtensionUpsert) UpdateCreatedAt() *ExtensionUpsert {
	u.SetExcluded(extension.FieldCreatedAt)
	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.Extension.Create().
//		OnConflict(
//			sql.ResolveWithNewValues(),
//			sql.ResolveWith(func(u *sql.UpdateSet) {
//				u.SetIgnore(extension.FieldID)
//			}),
//		).
//		Exec(ctx)
func (u *ExtensionUpsertOne) UpdateNewValues() *ExtensionUpsertOne {
	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(extension.FieldID)
		}
	}))
	return u
}

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

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

// SetVersion sets the "version" field.
func (u *ExtensionUpsertOne) SetVersion(v string) *ExtensionUpsertOne {
	return u.Update(func(s *ExtensionUpsert) {
		s.SetVersion(v)
	})
}

// UpdateVersion sets the "version" field to the value that was provided on create.
func (u *ExtensionUpsertOne) UpdateVersion() *ExtensionUpsertOne {
	return u.Update(func(s *ExtensionUpsert) {
		s.UpdateVersion()
	})
}

// SetPath sets the "path" field.
func (u *ExtensionUpsertOne) SetPath(v string) *ExtensionUpsertOne {
	return u.Update(func(s *ExtensionUpsert) {
		s.SetPath(v)
	})
}

// UpdatePath sets the "path" field to the value that was provided on create.
func (u *ExtensionUpsertOne) UpdatePath() *ExtensionUpsertOne {
	return u.Update(func(s *ExtensionUpsert) {
		s.UpdatePath()
	})
}

// SetCreatedAt sets the "created_at" field.
func (u *ExtensionUpsertOne) SetCreatedAt(v time.Time) *ExtensionUpsertOne {
	return u.Update(func(s *ExtensionUpsert) {
		s.SetCreatedAt(v)
	})
}

// UpdateCreatedAt sets the "created_at" field to the value that was provided on create.
func (u *ExtensionUpsertOne) UpdateCreatedAt() *ExtensionUpsertOne {
	return u.Update(func(s *ExtensionUpsert) {
		s.UpdateCreatedAt()
	})
}

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

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

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

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

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

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

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

// OnConflict allows configuring the `ON CONFLICT` / `ON DUPLICATE KEY` clause
// of the `INSERT` statement. For example:
//
//	client.Extension.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.ExtensionUpsert) {
//			SetVersion(v+v).
//		}).
//		Exec(ctx)
func (ecb *ExtensionCreateBulk) OnConflict(opts ...sql.ConflictOption) *ExtensionUpsertBulk {
	ecb.conflict = opts
	return &ExtensionUpsertBulk{
		create: ecb,
	}
}

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

// ExtensionUpsertBulk is the builder for "upsert"-ing
// a bulk of Extension nodes.
type ExtensionUpsertBulk struct {
	create *ExtensionCreateBulk
}

// UpdateNewValues updates the mutable fields using the new values that
// were set on create. Using this option is equivalent to using:
//
//	client.Extension.Create().
//		OnConflict(
//			sql.ResolveWithNewValues(),
//			sql.ResolveWith(func(u *sql.UpdateSet) {
//				u.SetIgnore(extension.FieldID)
//			}),
//		).
//		Exec(ctx)
func (u *ExtensionUpsertBulk) UpdateNewValues() *ExtensionUpsertBulk {
	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(extension.FieldID)
			}
		}
	}))
	return u
}

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

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

// SetVersion sets the "version" field.
func (u *ExtensionUpsertBulk) SetVersion(v string) *ExtensionUpsertBulk {
	return u.Update(func(s *ExtensionUpsert) {
		s.SetVersion(v)
	})
}

// UpdateVersion sets the "version" field to the value that was provided on create.
func (u *ExtensionUpsertBulk) UpdateVersion() *ExtensionUpsertBulk {
	return u.Update(func(s *ExtensionUpsert) {
		s.UpdateVersion()
	})
}

// SetPath sets the "path" field.
func (u *ExtensionUpsertBulk) SetPath(v string) *ExtensionUpsertBulk {
	return u.Update(func(s *ExtensionUpsert) {
		s.SetPath(v)
	})
}

// UpdatePath sets the "path" field to the value that was provided on create.
func (u *ExtensionUpsertBulk) UpdatePath() *ExtensionUpsertBulk {
	return u.Update(func(s *ExtensionUpsert) {
		s.UpdatePath()
	})
}

// SetCreatedAt sets the "created_at" field.
func (u *ExtensionUpsertBulk) SetCreatedAt(v time.Time) *ExtensionUpsertBulk {
	return u.Update(func(s *ExtensionUpsert) {
		s.SetCreatedAt(v)
	})
}

// UpdateCreatedAt sets the "created_at" field to the value that was provided on create.
func (u *ExtensionUpsertBulk) UpdateCreatedAt() *ExtensionUpsertBulk {
	return u.Update(func(s *ExtensionUpsert) {
		s.UpdateCreatedAt()
	})
}

// Exec executes the query.
func (u *ExtensionUpsertBulk) 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("db: OnConflict was set for builder %d. Set it on the ExtensionCreateBulk instead", i)
		}
	}
	if len(u.create.conflict) == 0 {
		return errors.New("db: missing options for ExtensionCreateBulk.OnConflict")
	}
	return u.create.Exec(ctx)
}

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