// 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/invitecode"
	"github.com/google/uuid"
)

// InviteCodeCreate is the builder for creating a InviteCode entity.
type InviteCodeCreate struct {
	config
	mutation *InviteCodeMutation
	hooks    []Hook
	conflict []sql.ConflictOption
}

// SetAdminID sets the "admin_id" field.
func (icc *InviteCodeCreate) SetAdminID(u uuid.UUID) *InviteCodeCreate {
	icc.mutation.SetAdminID(u)
	return icc
}

// SetCode sets the "code" field.
func (icc *InviteCodeCreate) SetCode(s string) *InviteCodeCreate {
	icc.mutation.SetCode(s)
	return icc
}

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

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

// SetUpdatedAt sets the "updated_at" field.
func (icc *InviteCodeCreate) SetUpdatedAt(t time.Time) *InviteCodeCreate {
	icc.mutation.SetUpdatedAt(t)
	return icc
}

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

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

// Mutation returns the InviteCodeMutation object of the builder.
func (icc *InviteCodeCreate) Mutation() *InviteCodeMutation {
	return icc.mutation
}

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

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

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

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

// defaults sets the default values of the builder before save.
func (icc *InviteCodeCreate) defaults() {
	if _, ok := icc.mutation.CreatedAt(); !ok {
		v := invitecode.DefaultCreatedAt()
		icc.mutation.SetCreatedAt(v)
	}
	if _, ok := icc.mutation.UpdatedAt(); !ok {
		v := invitecode.DefaultUpdatedAt()
		icc.mutation.SetUpdatedAt(v)
	}
}

// check runs all checks and user-defined validators on the builder.
func (icc *InviteCodeCreate) check() error {
	if _, ok := icc.mutation.AdminID(); !ok {
		return &ValidationError{Name: "admin_id", err: errors.New(`db: missing required field "InviteCode.admin_id"`)}
	}
	if _, ok := icc.mutation.Code(); !ok {
		return &ValidationError{Name: "code", err: errors.New(`db: missing required field "InviteCode.code"`)}
	}
	if _, ok := icc.mutation.CreatedAt(); !ok {
		return &ValidationError{Name: "created_at", err: errors.New(`db: missing required field "InviteCode.created_at"`)}
	}
	if _, ok := icc.mutation.UpdatedAt(); !ok {
		return &ValidationError{Name: "updated_at", err: errors.New(`db: missing required field "InviteCode.updated_at"`)}
	}
	return nil
}

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

func (icc *InviteCodeCreate) createSpec() (*InviteCode, *sqlgraph.CreateSpec) {
	var (
		_node = &InviteCode{config: icc.config}
		_spec = sqlgraph.NewCreateSpec(invitecode.Table, sqlgraph.NewFieldSpec(invitecode.FieldID, field.TypeUUID))
	)
	_spec.OnConflict = icc.conflict
	if id, ok := icc.mutation.ID(); ok {
		_node.ID = id
		_spec.ID.Value = &id
	}
	if value, ok := icc.mutation.AdminID(); ok {
		_spec.SetField(invitecode.FieldAdminID, field.TypeUUID, value)
		_node.AdminID = value
	}
	if value, ok := icc.mutation.Code(); ok {
		_spec.SetField(invitecode.FieldCode, field.TypeString, value)
		_node.Code = value
	}
	if value, ok := icc.mutation.CreatedAt(); ok {
		_spec.SetField(invitecode.FieldCreatedAt, field.TypeTime, value)
		_node.CreatedAt = value
	}
	if value, ok := icc.mutation.UpdatedAt(); ok {
		_spec.SetField(invitecode.FieldUpdatedAt, field.TypeTime, value)
		_node.UpdatedAt = value
	}
	return _node, _spec
}

// OnConflict allows configuring the `ON CONFLICT` / `ON DUPLICATE KEY` clause
// of the `INSERT` statement. For example:
//
//	client.InviteCode.Create().
//		SetAdminID(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.InviteCodeUpsert) {
//			SetAdminID(v+v).
//		}).
//		Exec(ctx)
func (icc *InviteCodeCreate) OnConflict(opts ...sql.ConflictOption) *InviteCodeUpsertOne {
	icc.conflict = opts
	return &InviteCodeUpsertOne{
		create: icc,
	}
}

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

type (
	// InviteCodeUpsertOne is the builder for "upsert"-ing
	//  one InviteCode node.
	InviteCodeUpsertOne struct {
		create *InviteCodeCreate
	}

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

// SetAdminID sets the "admin_id" field.
func (u *InviteCodeUpsert) SetAdminID(v uuid.UUID) *InviteCodeUpsert {
	u.Set(invitecode.FieldAdminID, v)
	return u
}

// UpdateAdminID sets the "admin_id" field to the value that was provided on create.
func (u *InviteCodeUpsert) UpdateAdminID() *InviteCodeUpsert {
	u.SetExcluded(invitecode.FieldAdminID)
	return u
}

// SetCode sets the "code" field.
func (u *InviteCodeUpsert) SetCode(v string) *InviteCodeUpsert {
	u.Set(invitecode.FieldCode, v)
	return u
}

// UpdateCode sets the "code" field to the value that was provided on create.
func (u *InviteCodeUpsert) UpdateCode() *InviteCodeUpsert {
	u.SetExcluded(invitecode.FieldCode)
	return u
}

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

// UpdateCreatedAt sets the "created_at" field to the value that was provided on create.
func (u *InviteCodeUpsert) UpdateCreatedAt() *InviteCodeUpsert {
	u.SetExcluded(invitecode.FieldCreatedAt)
	return u
}

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

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

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

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

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

// SetAdminID sets the "admin_id" field.
func (u *InviteCodeUpsertOne) SetAdminID(v uuid.UUID) *InviteCodeUpsertOne {
	return u.Update(func(s *InviteCodeUpsert) {
		s.SetAdminID(v)
	})
}

// UpdateAdminID sets the "admin_id" field to the value that was provided on create.
func (u *InviteCodeUpsertOne) UpdateAdminID() *InviteCodeUpsertOne {
	return u.Update(func(s *InviteCodeUpsert) {
		s.UpdateAdminID()
	})
}

// SetCode sets the "code" field.
func (u *InviteCodeUpsertOne) SetCode(v string) *InviteCodeUpsertOne {
	return u.Update(func(s *InviteCodeUpsert) {
		s.SetCode(v)
	})
}

// UpdateCode sets the "code" field to the value that was provided on create.
func (u *InviteCodeUpsertOne) UpdateCode() *InviteCodeUpsertOne {
	return u.Update(func(s *InviteCodeUpsert) {
		s.UpdateCode()
	})
}

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

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

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

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

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

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

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

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

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

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

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

// OnConflict allows configuring the `ON CONFLICT` / `ON DUPLICATE KEY` clause
// of the `INSERT` statement. For example:
//
//	client.InviteCode.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.InviteCodeUpsert) {
//			SetAdminID(v+v).
//		}).
//		Exec(ctx)
func (iccb *InviteCodeCreateBulk) OnConflict(opts ...sql.ConflictOption) *InviteCodeUpsertBulk {
	iccb.conflict = opts
	return &InviteCodeUpsertBulk{
		create: iccb,
	}
}

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

// InviteCodeUpsertBulk is the builder for "upsert"-ing
// a bulk of InviteCode nodes.
type InviteCodeUpsertBulk struct {
	create *InviteCodeCreateBulk
}

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

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

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

// SetAdminID sets the "admin_id" field.
func (u *InviteCodeUpsertBulk) SetAdminID(v uuid.UUID) *InviteCodeUpsertBulk {
	return u.Update(func(s *InviteCodeUpsert) {
		s.SetAdminID(v)
	})
}

// UpdateAdminID sets the "admin_id" field to the value that was provided on create.
func (u *InviteCodeUpsertBulk) UpdateAdminID() *InviteCodeUpsertBulk {
	return u.Update(func(s *InviteCodeUpsert) {
		s.UpdateAdminID()
	})
}

// SetCode sets the "code" field.
func (u *InviteCodeUpsertBulk) SetCode(v string) *InviteCodeUpsertBulk {
	return u.Update(func(s *InviteCodeUpsert) {
		s.SetCode(v)
	})
}

// UpdateCode sets the "code" field to the value that was provided on create.
func (u *InviteCodeUpsertBulk) UpdateCode() *InviteCodeUpsertBulk {
	return u.Update(func(s *InviteCodeUpsert) {
		s.UpdateCode()
	})
}

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

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

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

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

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

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