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

// UserAllowedGroupCreate is the builder for creating a UserAllowedGroup entity.
type UserAllowedGroupCreate struct {
	config
	mutation *UserAllowedGroupMutation
	hooks    []Hook
	conflict []sql.ConflictOption
}

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

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

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

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

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

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

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

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

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

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

// ExecX is like Exec, but panics if an error occurs.
func (_c *UserAllowedGroupCreate) 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 *UserAllowedGroupCreate) defaults() {
	if _, ok := _c.mutation.CreatedAt(); !ok {
		v := userallowedgroup.DefaultCreatedAt()
		_c.mutation.SetCreatedAt(v)
	}
}

// check runs all checks and user-defined validators on the builder.
func (_c *UserAllowedGroupCreate) check() error {
	if _, ok := _c.mutation.UserID(); !ok {
		return &ValidationError{Name: "user_id", err: errors.New(`ent: missing required field "UserAllowedGroup.user_id"`)}
	}
	if _, ok := _c.mutation.GroupID(); !ok {
		return &ValidationError{Name: "group_id", err: errors.New(`ent: missing required field "UserAllowedGroup.group_id"`)}
	}
	if _, ok := _c.mutation.CreatedAt(); !ok {
		return &ValidationError{Name: "created_at", err: errors.New(`ent: missing required field "UserAllowedGroup.created_at"`)}
	}
	if len(_c.mutation.UserIDs()) == 0 {
		return &ValidationError{Name: "user", err: errors.New(`ent: missing required edge "UserAllowedGroup.user"`)}
	}
	if len(_c.mutation.GroupIDs()) == 0 {
		return &ValidationError{Name: "group", err: errors.New(`ent: missing required edge "UserAllowedGroup.group"`)}
	}
	return nil
}

func (_c *UserAllowedGroupCreate) sqlSave(ctx context.Context) (*UserAllowedGroup, 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
	}
	return _node, nil
}

func (_c *UserAllowedGroupCreate) createSpec() (*UserAllowedGroup, *sqlgraph.CreateSpec) {
	var (
		_node = &UserAllowedGroup{config: _c.config}
		_spec = sqlgraph.NewCreateSpec(userallowedgroup.Table, nil)
	)
	_spec.OnConflict = _c.conflict
	if value, ok := _c.mutation.CreatedAt(); ok {
		_spec.SetField(userallowedgroup.FieldCreatedAt, field.TypeTime, value)
		_node.CreatedAt = value
	}
	if nodes := _c.mutation.UserIDs(); len(nodes) > 0 {
		edge := &sqlgraph.EdgeSpec{
			Rel:     sqlgraph.M2O,
			Inverse: false,
			Table:   userallowedgroup.UserTable,
			Columns: []string{userallowedgroup.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: false,
			Table:   userallowedgroup.GroupTable,
			Columns: []string{userallowedgroup.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)
	}
	return _node, _spec
}

// OnConflict allows configuring the `ON CONFLICT` / `ON DUPLICATE KEY` clause
// of the `INSERT` statement. For example:
//
//	client.UserAllowedGroup.Create().
//		SetUserID(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.UserAllowedGroupUpsert) {
//			SetUserID(v+v).
//		}).
//		Exec(ctx)
func (_c *UserAllowedGroupCreate) OnConflict(opts ...sql.ConflictOption) *UserAllowedGroupUpsertOne {
	_c.conflict = opts
	return &UserAllowedGroupUpsertOne{
		create: _c,
	}
}

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

type (
	// UserAllowedGroupUpsertOne is the builder for "upsert"-ing
	//  one UserAllowedGroup node.
	UserAllowedGroupUpsertOne struct {
		create *UserAllowedGroupCreate
	}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

// UserAllowedGroupUpsertBulk is the builder for "upsert"-ing
// a bulk of UserAllowedGroup nodes.
type UserAllowedGroupUpsertBulk struct {
	create *UserAllowedGroupCreateBulk
}

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

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

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

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

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

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

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

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

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