// Code generated by ent, DO NOT EDIT.

package db

import (
	"context"
	"errors"
	"fmt"

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

// UserGroupUserCreate is the builder for creating a UserGroupUser entity.
type UserGroupUserCreate struct {
	config
	mutation *UserGroupUserMutation
	hooks    []Hook
	conflict []sql.ConflictOption
}

// SetUserGroupID sets the "user_group_id" field.
func (uguc *UserGroupUserCreate) SetUserGroupID(u uuid.UUID) *UserGroupUserCreate {
	uguc.mutation.SetUserGroupID(u)
	return uguc
}

// SetUserID sets the "user_id" field.
func (uguc *UserGroupUserCreate) SetUserID(u uuid.UUID) *UserGroupUserCreate {
	uguc.mutation.SetUserID(u)
	return uguc
}

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

// SetUserGroup sets the "user_group" edge to the UserGroup entity.
func (uguc *UserGroupUserCreate) SetUserGroup(u *UserGroup) *UserGroupUserCreate {
	return uguc.SetUserGroupID(u.ID)
}

// SetUser sets the "user" edge to the User entity.
func (uguc *UserGroupUserCreate) SetUser(u *User) *UserGroupUserCreate {
	return uguc.SetUserID(u.ID)
}

// Mutation returns the UserGroupUserMutation object of the builder.
func (uguc *UserGroupUserCreate) Mutation() *UserGroupUserMutation {
	return uguc.mutation
}

// Save creates the UserGroupUser in the database.
func (uguc *UserGroupUserCreate) Save(ctx context.Context) (*UserGroupUser, error) {
	return withHooks(ctx, uguc.sqlSave, uguc.mutation, uguc.hooks)
}

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

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

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

// check runs all checks and user-defined validators on the builder.
func (uguc *UserGroupUserCreate) check() error {
	if _, ok := uguc.mutation.UserGroupID(); !ok {
		return &ValidationError{Name: "user_group_id", err: errors.New(`db: missing required field "UserGroupUser.user_group_id"`)}
	}
	if _, ok := uguc.mutation.UserID(); !ok {
		return &ValidationError{Name: "user_id", err: errors.New(`db: missing required field "UserGroupUser.user_id"`)}
	}
	if len(uguc.mutation.UserGroupIDs()) == 0 {
		return &ValidationError{Name: "user_group", err: errors.New(`db: missing required edge "UserGroupUser.user_group"`)}
	}
	if len(uguc.mutation.UserIDs()) == 0 {
		return &ValidationError{Name: "user", err: errors.New(`db: missing required edge "UserGroupUser.user"`)}
	}
	return nil
}

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

func (uguc *UserGroupUserCreate) createSpec() (*UserGroupUser, *sqlgraph.CreateSpec) {
	var (
		_node = &UserGroupUser{config: uguc.config}
		_spec = sqlgraph.NewCreateSpec(usergroupuser.Table, sqlgraph.NewFieldSpec(usergroupuser.FieldID, field.TypeUUID))
	)
	_spec.OnConflict = uguc.conflict
	if id, ok := uguc.mutation.ID(); ok {
		_node.ID = id
		_spec.ID.Value = &id
	}
	if nodes := uguc.mutation.UserGroupIDs(); len(nodes) > 0 {
		edge := &sqlgraph.EdgeSpec{
			Rel:     sqlgraph.M2O,
			Inverse: false,
			Table:   usergroupuser.UserGroupTable,
			Columns: []string{usergroupuser.UserGroupColumn},
			Bidi:    false,
			Target: &sqlgraph.EdgeTarget{
				IDSpec: sqlgraph.NewFieldSpec(usergroup.FieldID, field.TypeUUID),
			},
		}
		for _, k := range nodes {
			edge.Target.Nodes = append(edge.Target.Nodes, k)
		}
		_node.UserGroupID = nodes[0]
		_spec.Edges = append(_spec.Edges, edge)
	}
	if nodes := uguc.mutation.UserIDs(); len(nodes) > 0 {
		edge := &sqlgraph.EdgeSpec{
			Rel:     sqlgraph.M2O,
			Inverse: false,
			Table:   usergroupuser.UserTable,
			Columns: []string{usergroupuser.UserColumn},
			Bidi:    false,
			Target: &sqlgraph.EdgeTarget{
				IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeUUID),
			},
		}
		for _, k := range nodes {
			edge.Target.Nodes = append(edge.Target.Nodes, k)
		}
		_node.UserID = nodes[0]
		_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.UserGroupUser.Create().
//		SetUserGroupID(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.UserGroupUserUpsert) {
//			SetUserGroupID(v+v).
//		}).
//		Exec(ctx)
func (uguc *UserGroupUserCreate) OnConflict(opts ...sql.ConflictOption) *UserGroupUserUpsertOne {
	uguc.conflict = opts
	return &UserGroupUserUpsertOne{
		create: uguc,
	}
}

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

type (
	// UserGroupUserUpsertOne is the builder for "upsert"-ing
	//  one UserGroupUser node.
	UserGroupUserUpsertOne struct {
		create *UserGroupUserCreate
	}

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

// SetUserGroupID sets the "user_group_id" field.
func (u *UserGroupUserUpsert) SetUserGroupID(v uuid.UUID) *UserGroupUserUpsert {
	u.Set(usergroupuser.FieldUserGroupID, v)
	return u
}

// UpdateUserGroupID sets the "user_group_id" field to the value that was provided on create.
func (u *UserGroupUserUpsert) UpdateUserGroupID() *UserGroupUserUpsert {
	u.SetExcluded(usergroupuser.FieldUserGroupID)
	return u
}

// SetUserID sets the "user_id" field.
func (u *UserGroupUserUpsert) SetUserID(v uuid.UUID) *UserGroupUserUpsert {
	u.Set(usergroupuser.FieldUserID, v)
	return u
}

// UpdateUserID sets the "user_id" field to the value that was provided on create.
func (u *UserGroupUserUpsert) UpdateUserID() *UserGroupUserUpsert {
	u.SetExcluded(usergroupuser.FieldUserID)
	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.UserGroupUser.Create().
//		OnConflict(
//			sql.ResolveWithNewValues(),
//			sql.ResolveWith(func(u *sql.UpdateSet) {
//				u.SetIgnore(usergroupuser.FieldID)
//			}),
//		).
//		Exec(ctx)
func (u *UserGroupUserUpsertOne) UpdateNewValues() *UserGroupUserUpsertOne {
	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(usergroupuser.FieldID)
		}
	}))
	return u
}

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

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

// SetUserGroupID sets the "user_group_id" field.
func (u *UserGroupUserUpsertOne) SetUserGroupID(v uuid.UUID) *UserGroupUserUpsertOne {
	return u.Update(func(s *UserGroupUserUpsert) {
		s.SetUserGroupID(v)
	})
}

// UpdateUserGroupID sets the "user_group_id" field to the value that was provided on create.
func (u *UserGroupUserUpsertOne) UpdateUserGroupID() *UserGroupUserUpsertOne {
	return u.Update(func(s *UserGroupUserUpsert) {
		s.UpdateUserGroupID()
	})
}

// SetUserID sets the "user_id" field.
func (u *UserGroupUserUpsertOne) SetUserID(v uuid.UUID) *UserGroupUserUpsertOne {
	return u.Update(func(s *UserGroupUserUpsert) {
		s.SetUserID(v)
	})
}

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

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

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

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

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

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

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

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

// OnConflict allows configuring the `ON CONFLICT` / `ON DUPLICATE KEY` clause
// of the `INSERT` statement. For example:
//
//	client.UserGroupUser.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.UserGroupUserUpsert) {
//			SetUserGroupID(v+v).
//		}).
//		Exec(ctx)
func (ugucb *UserGroupUserCreateBulk) OnConflict(opts ...sql.ConflictOption) *UserGroupUserUpsertBulk {
	ugucb.conflict = opts
	return &UserGroupUserUpsertBulk{
		create: ugucb,
	}
}

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

// UserGroupUserUpsertBulk is the builder for "upsert"-ing
// a bulk of UserGroupUser nodes.
type UserGroupUserUpsertBulk struct {
	create *UserGroupUserCreateBulk
}

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

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

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

// SetUserGroupID sets the "user_group_id" field.
func (u *UserGroupUserUpsertBulk) SetUserGroupID(v uuid.UUID) *UserGroupUserUpsertBulk {
	return u.Update(func(s *UserGroupUserUpsert) {
		s.SetUserGroupID(v)
	})
}

// UpdateUserGroupID sets the "user_group_id" field to the value that was provided on create.
func (u *UserGroupUserUpsertBulk) UpdateUserGroupID() *UserGroupUserUpsertBulk {
	return u.Update(func(s *UserGroupUserUpsert) {
		s.UpdateUserGroupID()
	})
}

// SetUserID sets the "user_id" field.
func (u *UserGroupUserUpsertBulk) SetUserID(v uuid.UUID) *UserGroupUserUpsertBulk {
	return u.Update(func(s *UserGroupUserUpsert) {
		s.SetUserID(v)
	})
}

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

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

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