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

// UserGroupAdminCreate is the builder for creating a UserGroupAdmin entity.
type UserGroupAdminCreate struct {
	config
	mutation *UserGroupAdminMutation
	hooks    []Hook
	conflict []sql.ConflictOption
}

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

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

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

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

// SetAdmin sets the "admin" edge to the Admin entity.
func (ugac *UserGroupAdminCreate) SetAdmin(a *Admin) *UserGroupAdminCreate {
	return ugac.SetAdminID(a.ID)
}

// Mutation returns the UserGroupAdminMutation object of the builder.
func (ugac *UserGroupAdminCreate) Mutation() *UserGroupAdminMutation {
	return ugac.mutation
}

// Save creates the UserGroupAdmin in the database.
func (ugac *UserGroupAdminCreate) Save(ctx context.Context) (*UserGroupAdmin, error) {
	return withHooks(ctx, ugac.sqlSave, ugac.mutation, ugac.hooks)
}

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

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

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

// check runs all checks and user-defined validators on the builder.
func (ugac *UserGroupAdminCreate) check() error {
	if _, ok := ugac.mutation.UserGroupID(); !ok {
		return &ValidationError{Name: "user_group_id", err: errors.New(`db: missing required field "UserGroupAdmin.user_group_id"`)}
	}
	if _, ok := ugac.mutation.AdminID(); !ok {
		return &ValidationError{Name: "admin_id", err: errors.New(`db: missing required field "UserGroupAdmin.admin_id"`)}
	}
	if len(ugac.mutation.UserGroupIDs()) == 0 {
		return &ValidationError{Name: "user_group", err: errors.New(`db: missing required edge "UserGroupAdmin.user_group"`)}
	}
	if len(ugac.mutation.AdminIDs()) == 0 {
		return &ValidationError{Name: "admin", err: errors.New(`db: missing required edge "UserGroupAdmin.admin"`)}
	}
	return nil
}

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

func (ugac *UserGroupAdminCreate) createSpec() (*UserGroupAdmin, *sqlgraph.CreateSpec) {
	var (
		_node = &UserGroupAdmin{config: ugac.config}
		_spec = sqlgraph.NewCreateSpec(usergroupadmin.Table, sqlgraph.NewFieldSpec(usergroupadmin.FieldID, field.TypeUUID))
	)
	_spec.OnConflict = ugac.conflict
	if id, ok := ugac.mutation.ID(); ok {
		_node.ID = id
		_spec.ID.Value = &id
	}
	if nodes := ugac.mutation.UserGroupIDs(); len(nodes) > 0 {
		edge := &sqlgraph.EdgeSpec{
			Rel:     sqlgraph.M2O,
			Inverse: false,
			Table:   usergroupadmin.UserGroupTable,
			Columns: []string{usergroupadmin.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 := ugac.mutation.AdminIDs(); len(nodes) > 0 {
		edge := &sqlgraph.EdgeSpec{
			Rel:     sqlgraph.M2O,
			Inverse: false,
			Table:   usergroupadmin.AdminTable,
			Columns: []string{usergroupadmin.AdminColumn},
			Bidi:    false,
			Target: &sqlgraph.EdgeTarget{
				IDSpec: sqlgraph.NewFieldSpec(admin.FieldID, field.TypeUUID),
			},
		}
		for _, k := range nodes {
			edge.Target.Nodes = append(edge.Target.Nodes, k)
		}
		_node.AdminID = 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.UserGroupAdmin.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.UserGroupAdminUpsert) {
//			SetUserGroupID(v+v).
//		}).
//		Exec(ctx)
func (ugac *UserGroupAdminCreate) OnConflict(opts ...sql.ConflictOption) *UserGroupAdminUpsertOne {
	ugac.conflict = opts
	return &UserGroupAdminUpsertOne{
		create: ugac,
	}
}

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

type (
	// UserGroupAdminUpsertOne is the builder for "upsert"-ing
	//  one UserGroupAdmin node.
	UserGroupAdminUpsertOne struct {
		create *UserGroupAdminCreate
	}

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

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

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

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

// UpdateAdminID sets the "admin_id" field to the value that was provided on create.
func (u *UserGroupAdminUpsert) UpdateAdminID() *UserGroupAdminUpsert {
	u.SetExcluded(usergroupadmin.FieldAdminID)
	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.UserGroupAdmin.Create().
//		OnConflict(
//			sql.ResolveWithNewValues(),
//			sql.ResolveWith(func(u *sql.UpdateSet) {
//				u.SetIgnore(usergroupadmin.FieldID)
//			}),
//		).
//		Exec(ctx)
func (u *UserGroupAdminUpsertOne) UpdateNewValues() *UserGroupAdminUpsertOne {
	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(usergroupadmin.FieldID)
		}
	}))
	return u
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

// UserGroupAdminUpsertBulk is the builder for "upsert"-ing
// a bulk of UserGroupAdmin nodes.
type UserGroupAdminUpsertBulk struct {
	create *UserGroupAdminCreateBulk
}

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

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

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

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

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

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

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

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

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