// 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
}

// SetIPWhitelist sets the "ip_whitelist" field.
func (_c *APIKeyCreate) SetIPWhitelist(v []string) *APIKeyCreate {
	_c.mutation.SetIPWhitelist(v)
	return _c
}

// SetIPBlacklist sets the "ip_blacklist" field.
func (_c *APIKeyCreate) SetIPBlacklist(v []string) *APIKeyCreate {
	_c.mutation.SetIPBlacklist(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 value, ok := _c.mutation.IPWhitelist(); ok {
		_spec.SetField(apikey.FieldIPWhitelist, field.TypeJSON, value)
		_node.IPWhitelist = value
	}
	if value, ok := _c.mutation.IPBlacklist(); ok {
		_spec.SetField(apikey.FieldIPBlacklist, field.TypeJSON, value)
		_node.IPBlacklist = 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
}

// SetIPWhitelist sets the "ip_whitelist" field.
func (u *APIKeyUpsert) SetIPWhitelist(v []string) *APIKeyUpsert {
	u.Set(apikey.FieldIPWhitelist, v)
	return u
}

// UpdateIPWhitelist sets the "ip_whitelist" field to the value that was provided on create.
func (u *APIKeyUpsert) UpdateIPWhitelist() *APIKeyUpsert {
	u.SetExcluded(apikey.FieldIPWhitelist)
	return u
}

// ClearIPWhitelist clears the value of the "ip_whitelist" field.
func (u *APIKeyUpsert) ClearIPWhitelist() *APIKeyUpsert {
	u.SetNull(apikey.FieldIPWhitelist)
	return u
}

// SetIPBlacklist sets the "ip_blacklist" field.
func (u *APIKeyUpsert) SetIPBlacklist(v []string) *APIKeyUpsert {
	u.Set(apikey.FieldIPBlacklist, v)
	return u
}

// UpdateIPBlacklist sets the "ip_blacklist" field to the value that was provided on create.
func (u *APIKeyUpsert) UpdateIPBlacklist() *APIKeyUpsert {
	u.SetExcluded(apikey.FieldIPBlacklist)
	return u
}

// ClearIPBlacklist clears the value of the "ip_blacklist" field.
func (u *APIKeyUpsert) ClearIPBlacklist() *APIKeyUpsert {
	u.SetNull(apikey.FieldIPBlacklist)
	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()
	})
}

// SetIPWhitelist sets the "ip_whitelist" field.
func (u *APIKeyUpsertOne) SetIPWhitelist(v []string) *APIKeyUpsertOne {
	return u.Update(func(s *APIKeyUpsert) {
		s.SetIPWhitelist(v)
	})
}

// UpdateIPWhitelist sets the "ip_whitelist" field to the value that was provided on create.
func (u *APIKeyUpsertOne) UpdateIPWhitelist() *APIKeyUpsertOne {
	return u.Update(func(s *APIKeyUpsert) {
		s.UpdateIPWhitelist()
	})
}

// ClearIPWhitelist clears the value of the "ip_whitelist" field.
func (u *APIKeyUpsertOne) ClearIPWhitelist() *APIKeyUpsertOne {
	return u.Update(func(s *APIKeyUpsert) {
		s.ClearIPWhitelist()
	})
}

// SetIPBlacklist sets the "ip_blacklist" field.
func (u *APIKeyUpsertOne) SetIPBlacklist(v []string) *APIKeyUpsertOne {
	return u.Update(func(s *APIKeyUpsert) {
		s.SetIPBlacklist(v)
	})
}

// UpdateIPBlacklist sets the "ip_blacklist" field to the value that was provided on create.
func (u *APIKeyUpsertOne) UpdateIPBlacklist() *APIKeyUpsertOne {
	return u.Update(func(s *APIKeyUpsert) {
		s.UpdateIPBlacklist()
	})
}

// ClearIPBlacklist clears the value of the "ip_blacklist" field.
func (u *APIKeyUpsertOne) ClearIPBlacklist() *APIKeyUpsertOne {
	return u.Update(func(s *APIKeyUpsert) {
		s.ClearIPBlacklist()
	})
}

// 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()
	})
}

// SetIPWhitelist sets the "ip_whitelist" field.
func (u *APIKeyUpsertBulk) SetIPWhitelist(v []string) *APIKeyUpsertBulk {
	return u.Update(func(s *APIKeyUpsert) {
		s.SetIPWhitelist(v)
	})
}

// UpdateIPWhitelist sets the "ip_whitelist" field to the value that was provided on create.
func (u *APIKeyUpsertBulk) UpdateIPWhitelist() *APIKeyUpsertBulk {
	return u.Update(func(s *APIKeyUpsert) {
		s.UpdateIPWhitelist()
	})
}

// ClearIPWhitelist clears the value of the "ip_whitelist" field.
func (u *APIKeyUpsertBulk) ClearIPWhitelist() *APIKeyUpsertBulk {
	return u.Update(func(s *APIKeyUpsert) {
		s.ClearIPWhitelist()
	})
}

// SetIPBlacklist sets the "ip_blacklist" field.
func (u *APIKeyUpsertBulk) SetIPBlacklist(v []string) *APIKeyUpsertBulk {
	return u.Update(func(s *APIKeyUpsert) {
		s.SetIPBlacklist(v)
	})
}

// UpdateIPBlacklist sets the "ip_blacklist" field to the value that was provided on create.
func (u *APIKeyUpsertBulk) UpdateIPBlacklist() *APIKeyUpsertBulk {
	return u.Update(func(s *APIKeyUpsert) {
		s.UpdateIPBlacklist()
	})
}

// ClearIPBlacklist clears the value of the "ip_blacklist" field.
func (u *APIKeyUpsertBulk) ClearIPBlacklist() *APIKeyUpsertBulk {
	return u.Update(func(s *APIKeyUpsert) {
		s.ClearIPBlacklist()
	})
}

// 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)
	}
}
