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

// AccountGroupCreate is the builder for creating a AccountGroup entity.
type AccountGroupCreate struct {
	config
	mutation *AccountGroupMutation
	hooks    []Hook
	conflict []sql.ConflictOption
}

// SetAccountID sets the "account_id" field.
func (_c *AccountGroupCreate) SetAccountID(v int64) *AccountGroupCreate {
	_c.mutation.SetAccountID(v)
	return _c
}

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

// SetPriority sets the "priority" field.
func (_c *AccountGroupCreate) SetPriority(v int) *AccountGroupCreate {
	_c.mutation.SetPriority(v)
	return _c
}

// SetNillablePriority sets the "priority" field if the given value is not nil.
func (_c *AccountGroupCreate) SetNillablePriority(v *int) *AccountGroupCreate {
	if v != nil {
		_c.SetPriority(*v)
	}
	return _c
}

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

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

// SetAccount sets the "account" edge to the Account entity.
func (_c *AccountGroupCreate) SetAccount(v *Account) *AccountGroupCreate {
	return _c.SetAccountID(v.ID)
}

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

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

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

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

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

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

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

func (_c *AccountGroupCreate) sqlSave(ctx context.Context) (*AccountGroup, 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 *AccountGroupCreate) createSpec() (*AccountGroup, *sqlgraph.CreateSpec) {
	var (
		_node = &AccountGroup{config: _c.config}
		_spec = sqlgraph.NewCreateSpec(accountgroup.Table, nil)
	)
	_spec.OnConflict = _c.conflict
	if value, ok := _c.mutation.Priority(); ok {
		_spec.SetField(accountgroup.FieldPriority, field.TypeInt, value)
		_node.Priority = value
	}
	if value, ok := _c.mutation.CreatedAt(); ok {
		_spec.SetField(accountgroup.FieldCreatedAt, field.TypeTime, value)
		_node.CreatedAt = value
	}
	if nodes := _c.mutation.AccountIDs(); len(nodes) > 0 {
		edge := &sqlgraph.EdgeSpec{
			Rel:     sqlgraph.M2O,
			Inverse: false,
			Table:   accountgroup.AccountTable,
			Columns: []string{accountgroup.AccountColumn},
			Bidi:    false,
			Target: &sqlgraph.EdgeTarget{
				IDSpec: sqlgraph.NewFieldSpec(account.FieldID, field.TypeInt64),
			},
		}
		for _, k := range nodes {
			edge.Target.Nodes = append(edge.Target.Nodes, k)
		}
		_node.AccountID = 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:   accountgroup.GroupTable,
			Columns: []string{accountgroup.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.AccountGroup.Create().
//		SetAccountID(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.AccountGroupUpsert) {
//			SetAccountID(v+v).
//		}).
//		Exec(ctx)
func (_c *AccountGroupCreate) OnConflict(opts ...sql.ConflictOption) *AccountGroupUpsertOne {
	_c.conflict = opts
	return &AccountGroupUpsertOne{
		create: _c,
	}
}

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

type (
	// AccountGroupUpsertOne is the builder for "upsert"-ing
	//  one AccountGroup node.
	AccountGroupUpsertOne struct {
		create *AccountGroupCreate
	}

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

// SetAccountID sets the "account_id" field.
func (u *AccountGroupUpsert) SetAccountID(v int64) *AccountGroupUpsert {
	u.Set(accountgroup.FieldAccountID, v)
	return u
}

// UpdateAccountID sets the "account_id" field to the value that was provided on create.
func (u *AccountGroupUpsert) UpdateAccountID() *AccountGroupUpsert {
	u.SetExcluded(accountgroup.FieldAccountID)
	return u
}

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

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

// SetPriority sets the "priority" field.
func (u *AccountGroupUpsert) SetPriority(v int) *AccountGroupUpsert {
	u.Set(accountgroup.FieldPriority, v)
	return u
}

// UpdatePriority sets the "priority" field to the value that was provided on create.
func (u *AccountGroupUpsert) UpdatePriority() *AccountGroupUpsert {
	u.SetExcluded(accountgroup.FieldPriority)
	return u
}

// AddPriority adds v to the "priority" field.
func (u *AccountGroupUpsert) AddPriority(v int) *AccountGroupUpsert {
	u.Add(accountgroup.FieldPriority, v)
	return u
}

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

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

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

// SetAccountID sets the "account_id" field.
func (u *AccountGroupUpsertOne) SetAccountID(v int64) *AccountGroupUpsertOne {
	return u.Update(func(s *AccountGroupUpsert) {
		s.SetAccountID(v)
	})
}

// UpdateAccountID sets the "account_id" field to the value that was provided on create.
func (u *AccountGroupUpsertOne) UpdateAccountID() *AccountGroupUpsertOne {
	return u.Update(func(s *AccountGroupUpsert) {
		s.UpdateAccountID()
	})
}

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

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

// SetPriority sets the "priority" field.
func (u *AccountGroupUpsertOne) SetPriority(v int) *AccountGroupUpsertOne {
	return u.Update(func(s *AccountGroupUpsert) {
		s.SetPriority(v)
	})
}

// AddPriority adds v to the "priority" field.
func (u *AccountGroupUpsertOne) AddPriority(v int) *AccountGroupUpsertOne {
	return u.Update(func(s *AccountGroupUpsert) {
		s.AddPriority(v)
	})
}

// UpdatePriority sets the "priority" field to the value that was provided on create.
func (u *AccountGroupUpsertOne) UpdatePriority() *AccountGroupUpsertOne {
	return u.Update(func(s *AccountGroupUpsert) {
		s.UpdatePriority()
	})
}

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

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

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

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

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

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

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

// AccountGroupUpsertBulk is the builder for "upsert"-ing
// a bulk of AccountGroup nodes.
type AccountGroupUpsertBulk struct {
	create *AccountGroupCreateBulk
}

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

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

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

// SetAccountID sets the "account_id" field.
func (u *AccountGroupUpsertBulk) SetAccountID(v int64) *AccountGroupUpsertBulk {
	return u.Update(func(s *AccountGroupUpsert) {
		s.SetAccountID(v)
	})
}

// UpdateAccountID sets the "account_id" field to the value that was provided on create.
func (u *AccountGroupUpsertBulk) UpdateAccountID() *AccountGroupUpsertBulk {
	return u.Update(func(s *AccountGroupUpsert) {
		s.UpdateAccountID()
	})
}

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

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

// SetPriority sets the "priority" field.
func (u *AccountGroupUpsertBulk) SetPriority(v int) *AccountGroupUpsertBulk {
	return u.Update(func(s *AccountGroupUpsert) {
		s.SetPriority(v)
	})
}

// AddPriority adds v to the "priority" field.
func (u *AccountGroupUpsertBulk) AddPriority(v int) *AccountGroupUpsertBulk {
	return u.Update(func(s *AccountGroupUpsert) {
		s.AddPriority(v)
	})
}

// UpdatePriority sets the "priority" field to the value that was provided on create.
func (u *AccountGroupUpsertBulk) UpdatePriority() *AccountGroupUpsertBulk {
	return u.Update(func(s *AccountGroupUpsert) {
		s.UpdatePriority()
	})
}

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

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