// 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/member-gentei/member-gentei/gentei/ent/guild"
	"github.com/member-gentei/member-gentei/gentei/ent/guildrole"
	"github.com/member-gentei/member-gentei/gentei/ent/usermembership"
	"github.com/member-gentei/member-gentei/gentei/ent/youtubetalent"
)

// GuildRoleCreate is the builder for creating a GuildRole entity.
type GuildRoleCreate struct {
	config
	mutation *GuildRoleMutation
	hooks    []Hook
	conflict []sql.ConflictOption
}

// SetName sets the "name" field.
func (grc *GuildRoleCreate) SetName(s string) *GuildRoleCreate {
	grc.mutation.SetName(s)
	return grc
}

// SetLastUpdated sets the "last_updated" field.
func (grc *GuildRoleCreate) SetLastUpdated(t time.Time) *GuildRoleCreate {
	grc.mutation.SetLastUpdated(t)
	return grc
}

// SetNillableLastUpdated sets the "last_updated" field if the given value is not nil.
func (grc *GuildRoleCreate) SetNillableLastUpdated(t *time.Time) *GuildRoleCreate {
	if t != nil {
		grc.SetLastUpdated(*t)
	}
	return grc
}

// SetID sets the "id" field.
func (grc *GuildRoleCreate) SetID(u uint64) *GuildRoleCreate {
	grc.mutation.SetID(u)
	return grc
}

// SetGuildID sets the "guild" edge to the Guild entity by ID.
func (grc *GuildRoleCreate) SetGuildID(id uint64) *GuildRoleCreate {
	grc.mutation.SetGuildID(id)
	return grc
}

// SetGuild sets the "guild" edge to the Guild entity.
func (grc *GuildRoleCreate) SetGuild(g *Guild) *GuildRoleCreate {
	return grc.SetGuildID(g.ID)
}

// AddUserMembershipIDs adds the "user_memberships" edge to the UserMembership entity by IDs.
func (grc *GuildRoleCreate) AddUserMembershipIDs(ids ...int) *GuildRoleCreate {
	grc.mutation.AddUserMembershipIDs(ids...)
	return grc
}

// AddUserMemberships adds the "user_memberships" edges to the UserMembership entity.
func (grc *GuildRoleCreate) AddUserMemberships(u ...*UserMembership) *GuildRoleCreate {
	ids := make([]int, len(u))
	for i := range u {
		ids[i] = u[i].ID
	}
	return grc.AddUserMembershipIDs(ids...)
}

// SetTalentID sets the "talent" edge to the YouTubeTalent entity by ID.
func (grc *GuildRoleCreate) SetTalentID(id string) *GuildRoleCreate {
	grc.mutation.SetTalentID(id)
	return grc
}

// SetNillableTalentID sets the "talent" edge to the YouTubeTalent entity by ID if the given value is not nil.
func (grc *GuildRoleCreate) SetNillableTalentID(id *string) *GuildRoleCreate {
	if id != nil {
		grc = grc.SetTalentID(*id)
	}
	return grc
}

// SetTalent sets the "talent" edge to the YouTubeTalent entity.
func (grc *GuildRoleCreate) SetTalent(y *YouTubeTalent) *GuildRoleCreate {
	return grc.SetTalentID(y.ID)
}

// Mutation returns the GuildRoleMutation object of the builder.
func (grc *GuildRoleCreate) Mutation() *GuildRoleMutation {
	return grc.mutation
}

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

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

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

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

// defaults sets the default values of the builder before save.
func (grc *GuildRoleCreate) defaults() {
	if _, ok := grc.mutation.LastUpdated(); !ok {
		v := guildrole.DefaultLastUpdated()
		grc.mutation.SetLastUpdated(v)
	}
}

// check runs all checks and user-defined validators on the builder.
func (grc *GuildRoleCreate) check() error {
	if _, ok := grc.mutation.Name(); !ok {
		return &ValidationError{Name: "name", err: errors.New(`ent: missing required field "GuildRole.name"`)}
	}
	if _, ok := grc.mutation.LastUpdated(); !ok {
		return &ValidationError{Name: "last_updated", err: errors.New(`ent: missing required field "GuildRole.last_updated"`)}
	}
	if len(grc.mutation.GuildIDs()) == 0 {
		return &ValidationError{Name: "guild", err: errors.New(`ent: missing required edge "GuildRole.guild"`)}
	}
	return nil
}

func (grc *GuildRoleCreate) sqlSave(ctx context.Context) (*GuildRole, error) {
	if err := grc.check(); err != nil {
		return nil, err
	}
	_node, _spec := grc.createSpec()
	if err := sqlgraph.CreateNode(ctx, grc.driver, _spec); err != nil {
		if sqlgraph.IsConstraintError(err) {
			err = &ConstraintError{msg: err.Error(), wrap: err}
		}
		return nil, err
	}
	if _spec.ID.Value != _node.ID {
		id := _spec.ID.Value.(int64)
		_node.ID = uint64(id)
	}
	grc.mutation.id = &_node.ID
	grc.mutation.done = true
	return _node, nil
}

func (grc *GuildRoleCreate) createSpec() (*GuildRole, *sqlgraph.CreateSpec) {
	var (
		_node = &GuildRole{config: grc.config}
		_spec = sqlgraph.NewCreateSpec(guildrole.Table, sqlgraph.NewFieldSpec(guildrole.FieldID, field.TypeUint64))
	)
	_spec.OnConflict = grc.conflict
	if id, ok := grc.mutation.ID(); ok {
		_node.ID = id
		_spec.ID.Value = id
	}
	if value, ok := grc.mutation.Name(); ok {
		_spec.SetField(guildrole.FieldName, field.TypeString, value)
		_node.Name = value
	}
	if value, ok := grc.mutation.LastUpdated(); ok {
		_spec.SetField(guildrole.FieldLastUpdated, field.TypeTime, value)
		_node.LastUpdated = value
	}
	if nodes := grc.mutation.GuildIDs(); len(nodes) > 0 {
		edge := &sqlgraph.EdgeSpec{
			Rel:     sqlgraph.M2O,
			Inverse: true,
			Table:   guildrole.GuildTable,
			Columns: []string{guildrole.GuildColumn},
			Bidi:    false,
			Target: &sqlgraph.EdgeTarget{
				IDSpec: sqlgraph.NewFieldSpec(guild.FieldID, field.TypeUint64),
			},
		}
		for _, k := range nodes {
			edge.Target.Nodes = append(edge.Target.Nodes, k)
		}
		_node.guild_roles = &nodes[0]
		_spec.Edges = append(_spec.Edges, edge)
	}
	if nodes := grc.mutation.UserMembershipsIDs(); len(nodes) > 0 {
		edge := &sqlgraph.EdgeSpec{
			Rel:     sqlgraph.M2M,
			Inverse: true,
			Table:   guildrole.UserMembershipsTable,
			Columns: guildrole.UserMembershipsPrimaryKey,
			Bidi:    false,
			Target: &sqlgraph.EdgeTarget{
				IDSpec: sqlgraph.NewFieldSpec(usermembership.FieldID, field.TypeInt),
			},
		}
		for _, k := range nodes {
			edge.Target.Nodes = append(edge.Target.Nodes, k)
		}
		_spec.Edges = append(_spec.Edges, edge)
	}
	if nodes := grc.mutation.TalentIDs(); len(nodes) > 0 {
		edge := &sqlgraph.EdgeSpec{
			Rel:     sqlgraph.M2O,
			Inverse: true,
			Table:   guildrole.TalentTable,
			Columns: []string{guildrole.TalentColumn},
			Bidi:    false,
			Target: &sqlgraph.EdgeTarget{
				IDSpec: sqlgraph.NewFieldSpec(youtubetalent.FieldID, field.TypeString),
			},
		}
		for _, k := range nodes {
			edge.Target.Nodes = append(edge.Target.Nodes, k)
		}
		_node.you_tube_talent_roles = &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.GuildRole.Create().
//		SetName(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.GuildRoleUpsert) {
//			SetName(v+v).
//		}).
//		Exec(ctx)
func (grc *GuildRoleCreate) OnConflict(opts ...sql.ConflictOption) *GuildRoleUpsertOne {
	grc.conflict = opts
	return &GuildRoleUpsertOne{
		create: grc,
	}
}

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

type (
	// GuildRoleUpsertOne is the builder for "upsert"-ing
	//  one GuildRole node.
	GuildRoleUpsertOne struct {
		create *GuildRoleCreate
	}

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

// SetName sets the "name" field.
func (u *GuildRoleUpsert) SetName(v string) *GuildRoleUpsert {
	u.Set(guildrole.FieldName, v)
	return u
}

// UpdateName sets the "name" field to the value that was provided on create.
func (u *GuildRoleUpsert) UpdateName() *GuildRoleUpsert {
	u.SetExcluded(guildrole.FieldName)
	return u
}

// SetLastUpdated sets the "last_updated" field.
func (u *GuildRoleUpsert) SetLastUpdated(v time.Time) *GuildRoleUpsert {
	u.Set(guildrole.FieldLastUpdated, v)
	return u
}

// UpdateLastUpdated sets the "last_updated" field to the value that was provided on create.
func (u *GuildRoleUpsert) UpdateLastUpdated() *GuildRoleUpsert {
	u.SetExcluded(guildrole.FieldLastUpdated)
	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.GuildRole.Create().
//		OnConflict(
//			sql.ResolveWithNewValues(),
//			sql.ResolveWith(func(u *sql.UpdateSet) {
//				u.SetIgnore(guildrole.FieldID)
//			}),
//		).
//		Exec(ctx)
func (u *GuildRoleUpsertOne) UpdateNewValues() *GuildRoleUpsertOne {
	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(guildrole.FieldID)
		}
	}))
	return u
}

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

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

// SetName sets the "name" field.
func (u *GuildRoleUpsertOne) SetName(v string) *GuildRoleUpsertOne {
	return u.Update(func(s *GuildRoleUpsert) {
		s.SetName(v)
	})
}

// UpdateName sets the "name" field to the value that was provided on create.
func (u *GuildRoleUpsertOne) UpdateName() *GuildRoleUpsertOne {
	return u.Update(func(s *GuildRoleUpsert) {
		s.UpdateName()
	})
}

// SetLastUpdated sets the "last_updated" field.
func (u *GuildRoleUpsertOne) SetLastUpdated(v time.Time) *GuildRoleUpsertOne {
	return u.Update(func(s *GuildRoleUpsert) {
		s.SetLastUpdated(v)
	})
}

// UpdateLastUpdated sets the "last_updated" field to the value that was provided on create.
func (u *GuildRoleUpsertOne) UpdateLastUpdated() *GuildRoleUpsertOne {
	return u.Update(func(s *GuildRoleUpsert) {
		s.UpdateLastUpdated()
	})
}

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

// ExecX is like Exec, but panics if an error occurs.
func (u *GuildRoleUpsertOne) 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 *GuildRoleUpsertOne) ID(ctx context.Context) (id uint64, err error) {
	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 *GuildRoleUpsertOne) IDX(ctx context.Context) uint64 {
	id, err := u.ID(ctx)
	if err != nil {
		panic(err)
	}
	return id
}

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

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

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

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

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

// OnConflict allows configuring the `ON CONFLICT` / `ON DUPLICATE KEY` clause
// of the `INSERT` statement. For example:
//
//	client.GuildRole.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.GuildRoleUpsert) {
//			SetName(v+v).
//		}).
//		Exec(ctx)
func (grcb *GuildRoleCreateBulk) OnConflict(opts ...sql.ConflictOption) *GuildRoleUpsertBulk {
	grcb.conflict = opts
	return &GuildRoleUpsertBulk{
		create: grcb,
	}
}

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

// GuildRoleUpsertBulk is the builder for "upsert"-ing
// a bulk of GuildRole nodes.
type GuildRoleUpsertBulk struct {
	create *GuildRoleCreateBulk
}

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

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

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

// SetName sets the "name" field.
func (u *GuildRoleUpsertBulk) SetName(v string) *GuildRoleUpsertBulk {
	return u.Update(func(s *GuildRoleUpsert) {
		s.SetName(v)
	})
}

// UpdateName sets the "name" field to the value that was provided on create.
func (u *GuildRoleUpsertBulk) UpdateName() *GuildRoleUpsertBulk {
	return u.Update(func(s *GuildRoleUpsert) {
		s.UpdateName()
	})
}

// SetLastUpdated sets the "last_updated" field.
func (u *GuildRoleUpsertBulk) SetLastUpdated(v time.Time) *GuildRoleUpsertBulk {
	return u.Update(func(s *GuildRoleUpsert) {
		s.SetLastUpdated(v)
	})
}

// UpdateLastUpdated sets the "last_updated" field to the value that was provided on create.
func (u *GuildRoleUpsertBulk) UpdateLastUpdated() *GuildRoleUpsertBulk {
	return u.Update(func(s *GuildRoleUpsert) {
		s.UpdateLastUpdated()
	})
}

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

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