// 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/Wei-Shaw/sub2api/ent/apikey"
	"github.com/Wei-Shaw/sub2api/ent/group"
	"github.com/Wei-Shaw/sub2api/ent/usagelog"
	"github.com/Wei-Shaw/sub2api/ent/user"
)

// ApiKeyCreate is the builder for creating a ApiKey entity.
type ApiKeyCreate struct {
	config
	mutation *ApiKeyMutation
	hooks    []Hook
	conflict []sql.ConflictOption
}

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

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

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

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

// SetDeletedAt sets the "deleted_at" field.
func (_c *ApiKeyCreate) SetDeletedAt(v time.Time) *ApiKeyCreate {
	_c.mutation.SetDeletedAt(v)
	return _c
}

// SetNillableDeletedAt sets the "deleted_at" field if the given value is not nil.
func (_c *ApiKeyCreate) SetNillableDeletedAt(v *time.Time) *ApiKeyCreate {
	if v != nil {
		_c.SetDeletedAt(*v)
	}
	return _c
}

// SetUserID sets the "user_id" field.
func (_c *ApiKeyCreate) SetUserID(v int64) *ApiKeyCreate {
	_c.mutation.SetUserID(v)
	return _c
}

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

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

// SetGroupID sets the "group_id" field.
func (_c *ApiKeyCreate) SetGroupID(v int64) *ApiKeyCreate {
	_c.mutation.SetGroupID(v)
	return _c
}

// SetNillableGroupID sets the "group_id" field if the given value is not nil.
func (_c *ApiKeyCreate) SetNillableGroupID(v *int64) *ApiKeyCreate {
	if v != nil {
		_c.SetGroupID(*v)
	}
	return _c
}

// SetStatus sets the "status" field.
func (_c *ApiKeyCreate) SetStatus(v string) *ApiKeyCreate {
	_c.mutation.SetStatus(v)
	return _c
}

// SetNillableStatus sets the "status" field if the given value is not nil.
func (_c *ApiKeyCreate) SetNillableStatus(v *string) *ApiKeyCreate {
	if v != nil {
		_c.SetStatus(*v)
	}
	return _c
}

// SetUser sets the "user" edge to the User entity.
func (_c *ApiKeyCreate) SetUser(v *User) *ApiKeyCreate {
	return _c.SetUserID(v.ID)
}

// SetGroup sets the "group" edge to the Group entity.
func (_c *ApiKeyCreate) SetGroup(v *Group) *ApiKeyCreate {
	return _c.SetGroupID(v.ID)
}

// AddUsageLogIDs adds the "usage_logs" edge to the UsageLog entity by IDs.
func (_c *ApiKeyCreate) AddUsageLogIDs(ids ...int64) *ApiKeyCreate {
	_c.mutation.AddUsageLogIDs(ids...)
	return _c
}

// AddUsageLogs adds the "usage_logs" edges to the UsageLog entity.
func (_c *ApiKeyCreate) AddUsageLogs(v ...*UsageLog) *ApiKeyCreate {
	ids := make([]int64, len(v))
	for i := range v {
		ids[i] = v[i].ID
	}
	return _c.AddUsageLogIDs(ids...)
}

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

// Save creates the ApiKey in the database.
func (_c *ApiKeyCreate) Save(ctx context.Context) (*ApiKey, error) {
	if err := _c.defaults(); err != nil {
		return nil, err
	}
	return withHooks(ctx, _c.sqlSave, _c.mutation, _c.hooks)
}

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

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

// ExecX is like Exec, but panics if an error occurs.
func (_c *ApiKeyCreate) 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 *ApiKeyCreate) defaults() error {
	if _, ok := _c.mutation.CreatedAt(); !ok {
		if apikey.DefaultCreatedAt == nil {
			return fmt.Errorf("ent: uninitialized apikey.DefaultCreatedAt (forgotten import ent/runtime?)")
		}
		v := apikey.DefaultCreatedAt()
		_c.mutation.SetCreatedAt(v)
	}
	if _, ok := _c.mutation.UpdatedAt(); !ok {
		if apikey.DefaultUpdatedAt == nil {
			return fmt.Errorf("ent: uninitialized apikey.DefaultUpdatedAt (forgotten import ent/runtime?)")
		}
		v := apikey.DefaultUpdatedAt()
		_c.mutation.SetUpdatedAt(v)
	}
	if _, ok := _c.mutation.Status(); !ok {
		v := apikey.DefaultStatus
		_c.mutation.SetStatus(v)
	}
	return nil
}

// check runs all checks and user-defined validators on the builder.
func (_c *ApiKeyCreate) check() error {
	if _, ok := _c.mutation.CreatedAt(); !ok {
		return &ValidationError{Name: "created_at", err: errors.New(`ent: missing required field "ApiKey.created_at"`)}
	}
	if _, ok := _c.mutation.UpdatedAt(); !ok {
		return &ValidationError{Name: "updated_at", err: errors.New(`ent: missing required field "ApiKey.updated_at"`)}
	}
	if _, ok := _c.mutation.UserID(); !ok {
		return &ValidationError{Name: "user_id", err: errors.New(`ent: missing required field "ApiKey.user_id"`)}
	}
	if _, ok := _c.mutation.Key(); !ok {
		return &ValidationError{Name: "key", err: errors.New(`ent: missing required field "ApiKey.key"`)}
	}
	if v, ok := _c.mutation.Key(); ok {
		if err := apikey.KeyValidator(v); err != nil {
			return &ValidationError{Name: "key", err: fmt.Errorf(`ent: validator failed for field "ApiKey.key": %w`, err)}
		}
	}
	if _, ok := _c.mutation.Name(); !ok {
		return &ValidationError{Name: "name", err: errors.New(`ent: missing required field "ApiKey.name"`)}
	}
	if v, ok := _c.mutation.Name(); ok {
		if err := apikey.NameValidator(v); err != nil {
			return &ValidationError{Name: "name", err: fmt.Errorf(`ent: validator failed for field "ApiKey.name": %w`, err)}
		}
	}
	if _, ok := _c.mutation.Status(); !ok {
		return &ValidationError{Name: "status", err: errors.New(`ent: missing required field "ApiKey.status"`)}
	}
	if v, ok := _c.mutation.Status(); ok {
		if err := apikey.StatusValidator(v); err != nil {
			return &ValidationError{Name: "status", err: fmt.Errorf(`ent: validator failed for field "ApiKey.status": %w`, err)}
		}
	}
	if len(_c.mutation.UserIDs()) == 0 {
		return &ValidationError{Name: "user", err: errors.New(`ent: missing required edge "ApiKey.user"`)}
	}
	return nil
}

func (_c *ApiKeyCreate) sqlSave(ctx context.Context) (*ApiKey, 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 = int64(id)
	_c.mutation.id = &_node.ID
	_c.mutation.done = true
	return _node, nil
}

func (_c *ApiKeyCreate) createSpec() (*ApiKey, *sqlgraph.CreateSpec) {
	var (
		_node = &ApiKey{config: _c.config}
		_spec = sqlgraph.NewCreateSpec(apikey.Table, sqlgraph.NewFieldSpec(apikey.FieldID, field.TypeInt64))
	)
	_spec.OnConflict = _c.conflict
	if value, ok := _c.mutation.CreatedAt(); ok {
		_spec.SetField(apikey.FieldCreatedAt, field.TypeTime, value)
		_node.CreatedAt = value
	}
	if value, ok := _c.mutation.UpdatedAt(); ok {
		_spec.SetField(apikey.FieldUpdatedAt, field.TypeTime, value)
		_node.UpdatedAt = value
	}
	if value, ok := _c.mutation.DeletedAt(); ok {
		_spec.SetField(apikey.FieldDeletedAt, field.TypeTime, value)
		_node.DeletedAt = &value
	}
	if value, ok := _c.mutation.Key(); ok {
		_spec.SetField(apikey.FieldKey, field.TypeString, value)
		_node.Key = value
	}
	if value, ok := _c.mutation.Name(); ok {
		_spec.SetField(apikey.FieldName, field.TypeString, value)
		_node.Name = value
	}
	if value, ok := _c.mutation.Status(); ok {
		_spec.SetField(apikey.FieldStatus, field.TypeString, value)
		_node.Status = value
	}
	if nodes := _c.mutation.UserIDs(); len(nodes) > 0 {
		edge := &sqlgraph.EdgeSpec{
			Rel:     sqlgraph.M2O,
			Inverse: true,
			Table:   apikey.UserTable,
			Columns: []string{apikey.UserColumn},
			Bidi:    false,
			Target: &sqlgraph.EdgeTarget{
				IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeInt64),
			},
		}
		for _, k := range nodes {
			edge.Target.Nodes = append(edge.Target.Nodes, k)
		}
		_node.UserID = nodes[0]
		_spec.Edges = append(_spec.Edges, edge)
	}
	if nodes := _c.mutation.GroupIDs(); len(nodes) > 0 {
		edge := &sqlgraph.EdgeSpec{
			Rel:     sqlgraph.M2O,
			Inverse: true,
			Table:   apikey.GroupTable,
			Columns: []string{apikey.GroupColumn},
			Bidi:    false,
			Target: &sqlgraph.EdgeTarget{
				IDSpec: sqlgraph.NewFieldSpec(group.FieldID, field.TypeInt64),
			},
		}
		for _, k := range nodes {
			edge.Target.Nodes = append(edge.Target.Nodes, k)
		}
		_node.GroupID = &nodes[0]
		_spec.Edges = append(_spec.Edges, edge)
	}
	if nodes := _c.mutation.UsageLogsIDs(); len(nodes) > 0 {
		edge := &sqlgraph.EdgeSpec{
			Rel:     sqlgraph.O2M,
			Inverse: false,
			Table:   apikey.UsageLogsTable,
			Columns: []string{apikey.UsageLogsColumn},
			Bidi:    false,
			Target: &sqlgraph.EdgeTarget{
				IDSpec: sqlgraph.NewFieldSpec(usagelog.FieldID, field.TypeInt64),
			},
		}
		for _, k := range nodes {
			edge.Target.Nodes = append(edge.Target.Nodes, k)
		}
		_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.ApiKey.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.ApiKeyUpsert) {
//			SetCreatedAt(v+v).
//		}).
//		Exec(ctx)
func (_c *ApiKeyCreate) OnConflict(opts ...sql.ConflictOption) *ApiKeyUpsertOne {
	_c.conflict = opts
	return &ApiKeyUpsertOne{
		create: _c,
	}
}

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

type (
	// ApiKeyUpsertOne is the builder for "upsert"-ing
	//  one ApiKey node.
	ApiKeyUpsertOne struct {
		create *ApiKeyCreate
	}

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

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

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

// SetDeletedAt sets the "deleted_at" field.
func (u *ApiKeyUpsert) SetDeletedAt(v time.Time) *ApiKeyUpsert {
	u.Set(apikey.FieldDeletedAt, v)
	return u
}

// UpdateDeletedAt sets the "deleted_at" field to the value that was provided on create.
func (u *ApiKeyUpsert) UpdateDeletedAt() *ApiKeyUpsert {
	u.SetExcluded(apikey.FieldDeletedAt)
	return u
}

// ClearDeletedAt clears the value of the "deleted_at" field.
func (u *ApiKeyUpsert) ClearDeletedAt() *ApiKeyUpsert {
	u.SetNull(apikey.FieldDeletedAt)
	return u
}

// SetUserID sets the "user_id" field.
func (u *ApiKeyUpsert) SetUserID(v int64) *ApiKeyUpsert {
	u.Set(apikey.FieldUserID, v)
	return u
}

// UpdateUserID sets the "user_id" field to the value that was provided on create.
func (u *ApiKeyUpsert) UpdateUserID() *ApiKeyUpsert {
	u.SetExcluded(apikey.FieldUserID)
	return u
}

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

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

// SetName sets the "name" field.
func (u *ApiKeyUpsert) SetName(v string) *ApiKeyUpsert {
	u.Set(apikey.FieldName, v)
	return u
}

// UpdateName sets the "name" field to the value that was provided on create.
func (u *ApiKeyUpsert) UpdateName() *ApiKeyUpsert {
	u.SetExcluded(apikey.FieldName)
	return u
}

// SetGroupID sets the "group_id" field.
func (u *ApiKeyUpsert) SetGroupID(v int64) *ApiKeyUpsert {
	u.Set(apikey.FieldGroupID, v)
	return u
}

// UpdateGroupID sets the "group_id" field to the value that was provided on create.
func (u *ApiKeyUpsert) UpdateGroupID() *ApiKeyUpsert {
	u.SetExcluded(apikey.FieldGroupID)
	return u
}

// ClearGroupID clears the value of the "group_id" field.
func (u *ApiKeyUpsert) ClearGroupID() *ApiKeyUpsert {
	u.SetNull(apikey.FieldGroupID)
	return u
}

// SetStatus sets the "status" field.
func (u *ApiKeyUpsert) SetStatus(v string) *ApiKeyUpsert {
	u.Set(apikey.FieldStatus, v)
	return u
}

// UpdateStatus sets the "status" field to the value that was provided on create.
func (u *ApiKeyUpsert) UpdateStatus() *ApiKeyUpsert {
	u.SetExcluded(apikey.FieldStatus)
	return u
}

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

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

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

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

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

// SetDeletedAt sets the "deleted_at" field.
func (u *ApiKeyUpsertOne) SetDeletedAt(v time.Time) *ApiKeyUpsertOne {
	return u.Update(func(s *ApiKeyUpsert) {
		s.SetDeletedAt(v)
	})
}

// UpdateDeletedAt sets the "deleted_at" field to the value that was provided on create.
func (u *ApiKeyUpsertOne) UpdateDeletedAt() *ApiKeyUpsertOne {
	return u.Update(func(s *ApiKeyUpsert) {
		s.UpdateDeletedAt()
	})
}

// ClearDeletedAt clears the value of the "deleted_at" field.
func (u *ApiKeyUpsertOne) ClearDeletedAt() *ApiKeyUpsertOne {
	return u.Update(func(s *ApiKeyUpsert) {
		s.ClearDeletedAt()
	})
}

// SetUserID sets the "user_id" field.
func (u *ApiKeyUpsertOne) SetUserID(v int64) *ApiKeyUpsertOne {
	return u.Update(func(s *ApiKeyUpsert) {
		s.SetUserID(v)
	})
}

// UpdateUserID sets the "user_id" field to the value that was provided on create.
func (u *ApiKeyUpsertOne) UpdateUserID() *ApiKeyUpsertOne {
	return u.Update(func(s *ApiKeyUpsert) {
		s.UpdateUserID()
	})
}

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

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

// SetName sets the "name" field.
func (u *ApiKeyUpsertOne) SetName(v string) *ApiKeyUpsertOne {
	return u.Update(func(s *ApiKeyUpsert) {
		s.SetName(v)
	})
}

// UpdateName sets the "name" field to the value that was provided on create.
func (u *ApiKeyUpsertOne) UpdateName() *ApiKeyUpsertOne {
	return u.Update(func(s *ApiKeyUpsert) {
		s.UpdateName()
	})
}

// SetGroupID sets the "group_id" field.
func (u *ApiKeyUpsertOne) SetGroupID(v int64) *ApiKeyUpsertOne {
	return u.Update(func(s *ApiKeyUpsert) {
		s.SetGroupID(v)
	})
}

// UpdateGroupID sets the "group_id" field to the value that was provided on create.
func (u *ApiKeyUpsertOne) UpdateGroupID() *ApiKeyUpsertOne {
	return u.Update(func(s *ApiKeyUpsert) {
		s.UpdateGroupID()
	})
}

// ClearGroupID clears the value of the "group_id" field.
func (u *ApiKeyUpsertOne) ClearGroupID() *ApiKeyUpsertOne {
	return u.Update(func(s *ApiKeyUpsert) {
		s.ClearGroupID()
	})
}

// SetStatus sets the "status" field.
func (u *ApiKeyUpsertOne) SetStatus(v string) *ApiKeyUpsertOne {
	return u.Update(func(s *ApiKeyUpsert) {
		s.SetStatus(v)
	})
}

// UpdateStatus sets the "status" field to the value that was provided on create.
func (u *ApiKeyUpsertOne) UpdateStatus() *ApiKeyUpsertOne {
	return u.Update(func(s *ApiKeyUpsert) {
		s.UpdateStatus()
	})
}

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

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

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

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

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

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

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

// ApiKeyUpsertBulk is the builder for "upsert"-ing
// a bulk of ApiKey nodes.
type ApiKeyUpsertBulk struct {
	create *ApiKeyCreateBulk
}

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

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

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

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

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

// SetDeletedAt sets the "deleted_at" field.
func (u *ApiKeyUpsertBulk) SetDeletedAt(v time.Time) *ApiKeyUpsertBulk {
	return u.Update(func(s *ApiKeyUpsert) {
		s.SetDeletedAt(v)
	})
}

// UpdateDeletedAt sets the "deleted_at" field to the value that was provided on create.
func (u *ApiKeyUpsertBulk) UpdateDeletedAt() *ApiKeyUpsertBulk {
	return u.Update(func(s *ApiKeyUpsert) {
		s.UpdateDeletedAt()
	})
}

// ClearDeletedAt clears the value of the "deleted_at" field.
func (u *ApiKeyUpsertBulk) ClearDeletedAt() *ApiKeyUpsertBulk {
	return u.Update(func(s *ApiKeyUpsert) {
		s.ClearDeletedAt()
	})
}

// SetUserID sets the "user_id" field.
func (u *ApiKeyUpsertBulk) SetUserID(v int64) *ApiKeyUpsertBulk {
	return u.Update(func(s *ApiKeyUpsert) {
		s.SetUserID(v)
	})
}

// UpdateUserID sets the "user_id" field to the value that was provided on create.
func (u *ApiKeyUpsertBulk) UpdateUserID() *ApiKeyUpsertBulk {
	return u.Update(func(s *ApiKeyUpsert) {
		s.UpdateUserID()
	})
}

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

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

// SetName sets the "name" field.
func (u *ApiKeyUpsertBulk) SetName(v string) *ApiKeyUpsertBulk {
	return u.Update(func(s *ApiKeyUpsert) {
		s.SetName(v)
	})
}

// UpdateName sets the "name" field to the value that was provided on create.
func (u *ApiKeyUpsertBulk) UpdateName() *ApiKeyUpsertBulk {
	return u.Update(func(s *ApiKeyUpsert) {
		s.UpdateName()
	})
}

// SetGroupID sets the "group_id" field.
func (u *ApiKeyUpsertBulk) SetGroupID(v int64) *ApiKeyUpsertBulk {
	return u.Update(func(s *ApiKeyUpsert) {
		s.SetGroupID(v)
	})
}

// UpdateGroupID sets the "group_id" field to the value that was provided on create.
func (u *ApiKeyUpsertBulk) UpdateGroupID() *ApiKeyUpsertBulk {
	return u.Update(func(s *ApiKeyUpsert) {
		s.UpdateGroupID()
	})
}

// ClearGroupID clears the value of the "group_id" field.
func (u *ApiKeyUpsertBulk) ClearGroupID() *ApiKeyUpsertBulk {
	return u.Update(func(s *ApiKeyUpsert) {
		s.ClearGroupID()
	})
}

// SetStatus sets the "status" field.
func (u *ApiKeyUpsertBulk) SetStatus(v string) *ApiKeyUpsertBulk {
	return u.Update(func(s *ApiKeyUpsert) {
		s.SetStatus(v)
	})
}

// UpdateStatus sets the "status" field to the value that was provided on create.
func (u *ApiKeyUpsertBulk) UpdateStatus() *ApiKeyUpsertBulk {
	return u.Update(func(s *ApiKeyUpsert) {
		s.UpdateStatus()
	})
}

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

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