// Code generated by ent, DO NOT EDIT.

package ent

import (
	"context"
	"errors"
	"fmt"

	"entgo.io/ent/dialect/sql"
	"entgo.io/ent/dialect/sql/sqlgraph"
	"entgo.io/ent/schema/field"
	"github.com/anzhiyu-c/anheyu-app/ent/link"
	"github.com/anzhiyu-c/anheyu-app/ent/linktag"
)

// LinkTagCreate is the builder for creating a LinkTag entity.
type LinkTagCreate struct {
	config
	mutation *LinkTagMutation
	hooks    []Hook
	conflict []sql.ConflictOption
}

// SetName sets the "name" field.
func (_c *LinkTagCreate) SetName(v string) *LinkTagCreate {
	_c.mutation.SetName(v)
	return _c
}

// SetColor sets the "color" field.
func (_c *LinkTagCreate) SetColor(v string) *LinkTagCreate {
	_c.mutation.SetColor(v)
	return _c
}

// SetNillableColor sets the "color" field if the given value is not nil.
func (_c *LinkTagCreate) SetNillableColor(v *string) *LinkTagCreate {
	if v != nil {
		_c.SetColor(*v)
	}
	return _c
}

// AddLinkIDs adds the "links" edge to the Link entity by IDs.
func (_c *LinkTagCreate) AddLinkIDs(ids ...int) *LinkTagCreate {
	_c.mutation.AddLinkIDs(ids...)
	return _c
}

// AddLinks adds the "links" edges to the Link entity.
func (_c *LinkTagCreate) AddLinks(v ...*Link) *LinkTagCreate {
	ids := make([]int, len(v))
	for i := range v {
		ids[i] = v[i].ID
	}
	return _c.AddLinkIDs(ids...)
}

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

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

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

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

// ExecX is like Exec, but panics if an error occurs.
func (_c *LinkTagCreate) 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 *LinkTagCreate) defaults() {
	if _, ok := _c.mutation.Color(); !ok {
		v := linktag.DefaultColor
		_c.mutation.SetColor(v)
	}
}

// check runs all checks and user-defined validators on the builder.
func (_c *LinkTagCreate) check() error {
	if _, ok := _c.mutation.Name(); !ok {
		return &ValidationError{Name: "name", err: errors.New(`ent: missing required field "LinkTag.name"`)}
	}
	if v, ok := _c.mutation.Name(); ok {
		if err := linktag.NameValidator(v); err != nil {
			return &ValidationError{Name: "name", err: fmt.Errorf(`ent: validator failed for field "LinkTag.name": %w`, err)}
		}
	}
	if _, ok := _c.mutation.Color(); !ok {
		return &ValidationError{Name: "color", err: errors.New(`ent: missing required field "LinkTag.color"`)}
	}
	return nil
}

func (_c *LinkTagCreate) sqlSave(ctx context.Context) (*LinkTag, 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
	}
	id := _spec.ID.Value.(int64)
	_node.ID = int(id)
	_c.mutation.id = &_node.ID
	_c.mutation.done = true
	return _node, nil
}

func (_c *LinkTagCreate) createSpec() (*LinkTag, *sqlgraph.CreateSpec) {
	var (
		_node = &LinkTag{config: _c.config}
		_spec = sqlgraph.NewCreateSpec(linktag.Table, sqlgraph.NewFieldSpec(linktag.FieldID, field.TypeInt))
	)
	_spec.OnConflict = _c.conflict
	if value, ok := _c.mutation.Name(); ok {
		_spec.SetField(linktag.FieldName, field.TypeString, value)
		_node.Name = value
	}
	if value, ok := _c.mutation.Color(); ok {
		_spec.SetField(linktag.FieldColor, field.TypeString, value)
		_node.Color = value
	}
	if nodes := _c.mutation.LinksIDs(); len(nodes) > 0 {
		edge := &sqlgraph.EdgeSpec{
			Rel:     sqlgraph.M2M,
			Inverse: true,
			Table:   linktag.LinksTable,
			Columns: linktag.LinksPrimaryKey,
			Bidi:    false,
			Target: &sqlgraph.EdgeTarget{
				IDSpec: sqlgraph.NewFieldSpec(link.FieldID, field.TypeInt),
			},
		}
		for _, k := range nodes {
			edge.Target.Nodes = append(edge.Target.Nodes, k)
		}
		_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.LinkTag.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.LinkTagUpsert) {
//			SetName(v+v).
//		}).
//		Exec(ctx)
func (_c *LinkTagCreate) OnConflict(opts ...sql.ConflictOption) *LinkTagUpsertOne {
	_c.conflict = opts
	return &LinkTagUpsertOne{
		create: _c,
	}
}

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

type (
	// LinkTagUpsertOne is the builder for "upsert"-ing
	//  one LinkTag node.
	LinkTagUpsertOne struct {
		create *LinkTagCreate
	}

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

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

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

// SetColor sets the "color" field.
func (u *LinkTagUpsert) SetColor(v string) *LinkTagUpsert {
	u.Set(linktag.FieldColor, v)
	return u
}

// UpdateColor sets the "color" field to the value that was provided on create.
func (u *LinkTagUpsert) UpdateColor() *LinkTagUpsert {
	u.SetExcluded(linktag.FieldColor)
	return u
}

// UpdateNewValues updates the mutable fields using the new values that were set on create.
// Using this option is equivalent to using:
//
//	client.LinkTag.Create().
//		OnConflict(
//			sql.ResolveWithNewValues(),
//		).
//		Exec(ctx)
func (u *LinkTagUpsertOne) UpdateNewValues() *LinkTagUpsertOne {
	u.create.conflict = append(u.create.conflict, sql.ResolveWithNewValues())
	return u
}

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

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

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

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

// SetColor sets the "color" field.
func (u *LinkTagUpsertOne) SetColor(v string) *LinkTagUpsertOne {
	return u.Update(func(s *LinkTagUpsert) {
		s.SetColor(v)
	})
}

// UpdateColor sets the "color" field to the value that was provided on create.
func (u *LinkTagUpsertOne) UpdateColor() *LinkTagUpsertOne {
	return u.Update(func(s *LinkTagUpsert) {
		s.UpdateColor()
	})
}

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

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

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

// Save creates the LinkTag entities in the database.
func (_c *LinkTagCreateBulk) Save(ctx context.Context) ([]*LinkTag, error) {
	if _c.err != nil {
		return nil, _c.err
	}
	specs := make([]*sqlgraph.CreateSpec, len(_c.builders))
	nodes := make([]*LinkTag, 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.(*LinkTagMutation)
				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.id = &nodes[i].ID
				if specs[i].ID.Value != nil {
					id := specs[i].ID.Value.(int64)
					nodes[i].ID = int(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, _c.builders[0].mutation); err != nil {
			return nil, err
		}
	}
	return nodes, nil
}

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

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

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

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

// LinkTagUpsertBulk is the builder for "upsert"-ing
// a bulk of LinkTag nodes.
type LinkTagUpsertBulk struct {
	create *LinkTagCreateBulk
}

// UpdateNewValues updates the mutable fields using the new values that
// were set on create. Using this option is equivalent to using:
//
//	client.LinkTag.Create().
//		OnConflict(
//			sql.ResolveWithNewValues(),
//		).
//		Exec(ctx)
func (u *LinkTagUpsertBulk) UpdateNewValues() *LinkTagUpsertBulk {
	u.create.conflict = append(u.create.conflict, sql.ResolveWithNewValues())
	return u
}

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

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

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

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

// SetColor sets the "color" field.
func (u *LinkTagUpsertBulk) SetColor(v string) *LinkTagUpsertBulk {
	return u.Update(func(s *LinkTagUpsert) {
		s.SetColor(v)
	})
}

// UpdateColor sets the "color" field to the value that was provided on create.
func (u *LinkTagUpsertBulk) UpdateColor() *LinkTagUpsertBulk {
	return u.Update(func(s *LinkTagUpsert) {
		s.UpdateColor()
	})
}

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

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