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

// AdminRoleCreate is the builder for creating a AdminRole entity.
type AdminRoleCreate struct {
	config
	mutation *AdminRoleMutation
	hooks    []Hook
	conflict []sql.ConflictOption
}

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

// SetRoleID sets the "role_id" field.
func (arc *AdminRoleCreate) SetRoleID(i int64) *AdminRoleCreate {
	arc.mutation.SetRoleID(i)
	return arc
}

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

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

// SetRole sets the "role" edge to the Role entity.
func (arc *AdminRoleCreate) SetRole(r *Role) *AdminRoleCreate {
	return arc.SetRoleID(r.ID)
}

// Mutation returns the AdminRoleMutation object of the builder.
func (arc *AdminRoleCreate) Mutation() *AdminRoleMutation {
	return arc.mutation
}

// Save creates the AdminRole in the database.
func (arc *AdminRoleCreate) Save(ctx context.Context) (*AdminRole, error) {
	return withHooks(ctx, arc.sqlSave, arc.mutation, arc.hooks)
}

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

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

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

// check runs all checks and user-defined validators on the builder.
func (arc *AdminRoleCreate) check() error {
	if _, ok := arc.mutation.AdminID(); !ok {
		return &ValidationError{Name: "admin_id", err: errors.New(`db: missing required field "AdminRole.admin_id"`)}
	}
	if _, ok := arc.mutation.RoleID(); !ok {
		return &ValidationError{Name: "role_id", err: errors.New(`db: missing required field "AdminRole.role_id"`)}
	}
	if len(arc.mutation.AdminIDs()) == 0 {
		return &ValidationError{Name: "admin", err: errors.New(`db: missing required edge "AdminRole.admin"`)}
	}
	if len(arc.mutation.RoleIDs()) == 0 {
		return &ValidationError{Name: "role", err: errors.New(`db: missing required edge "AdminRole.role"`)}
	}
	return nil
}

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

func (arc *AdminRoleCreate) createSpec() (*AdminRole, *sqlgraph.CreateSpec) {
	var (
		_node = &AdminRole{config: arc.config}
		_spec = sqlgraph.NewCreateSpec(adminrole.Table, sqlgraph.NewFieldSpec(adminrole.FieldID, field.TypeUUID))
	)
	_spec.OnConflict = arc.conflict
	if id, ok := arc.mutation.ID(); ok {
		_node.ID = id
		_spec.ID.Value = &id
	}
	if nodes := arc.mutation.AdminIDs(); len(nodes) > 0 {
		edge := &sqlgraph.EdgeSpec{
			Rel:     sqlgraph.M2O,
			Inverse: false,
			Table:   adminrole.AdminTable,
			Columns: []string{adminrole.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)
	}
	if nodes := arc.mutation.RoleIDs(); len(nodes) > 0 {
		edge := &sqlgraph.EdgeSpec{
			Rel:     sqlgraph.M2O,
			Inverse: false,
			Table:   adminrole.RoleTable,
			Columns: []string{adminrole.RoleColumn},
			Bidi:    false,
			Target: &sqlgraph.EdgeTarget{
				IDSpec: sqlgraph.NewFieldSpec(role.FieldID, field.TypeInt64),
			},
		}
		for _, k := range nodes {
			edge.Target.Nodes = append(edge.Target.Nodes, k)
		}
		_node.RoleID = 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.AdminRole.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.AdminRoleUpsert) {
//			SetAdminID(v+v).
//		}).
//		Exec(ctx)
func (arc *AdminRoleCreate) OnConflict(opts ...sql.ConflictOption) *AdminRoleUpsertOne {
	arc.conflict = opts
	return &AdminRoleUpsertOne{
		create: arc,
	}
}

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

type (
	// AdminRoleUpsertOne is the builder for "upsert"-ing
	//  one AdminRole node.
	AdminRoleUpsertOne struct {
		create *AdminRoleCreate
	}

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

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

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

// SetRoleID sets the "role_id" field.
func (u *AdminRoleUpsert) SetRoleID(v int64) *AdminRoleUpsert {
	u.Set(adminrole.FieldRoleID, v)
	return u
}

// UpdateRoleID sets the "role_id" field to the value that was provided on create.
func (u *AdminRoleUpsert) UpdateRoleID() *AdminRoleUpsert {
	u.SetExcluded(adminrole.FieldRoleID)
	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.AdminRole.Create().
//		OnConflict(
//			sql.ResolveWithNewValues(),
//			sql.ResolveWith(func(u *sql.UpdateSet) {
//				u.SetIgnore(adminrole.FieldID)
//			}),
//		).
//		Exec(ctx)
func (u *AdminRoleUpsertOne) UpdateNewValues() *AdminRoleUpsertOne {
	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(adminrole.FieldID)
		}
	}))
	return u
}

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

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

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

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

// SetRoleID sets the "role_id" field.
func (u *AdminRoleUpsertOne) SetRoleID(v int64) *AdminRoleUpsertOne {
	return u.Update(func(s *AdminRoleUpsert) {
		s.SetRoleID(v)
	})
}

// UpdateRoleID sets the "role_id" field to the value that was provided on create.
func (u *AdminRoleUpsertOne) UpdateRoleID() *AdminRoleUpsertOne {
	return u.Update(func(s *AdminRoleUpsert) {
		s.UpdateRoleID()
	})
}

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

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

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

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

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

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

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

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

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

// AdminRoleUpsertBulk is the builder for "upsert"-ing
// a bulk of AdminRole nodes.
type AdminRoleUpsertBulk struct {
	create *AdminRoleCreateBulk
}

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

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

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

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

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

// SetRoleID sets the "role_id" field.
func (u *AdminRoleUpsertBulk) SetRoleID(v int64) *AdminRoleUpsertBulk {
	return u.Update(func(s *AdminRoleUpsert) {
		s.SetRoleID(v)
	})
}

// UpdateRoleID sets the "role_id" field to the value that was provided on create.
func (u *AdminRoleUpsertBulk) UpdateRoleID() *AdminRoleUpsertBulk {
	return u.Update(func(s *AdminRoleUpsert) {
		s.UpdateRoleID()
	})
}

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

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