// 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/linkcategory"
)

// LinkCategoryCreate is the builder for creating a LinkCategory entity.
type LinkCategoryCreate struct {
	config
	mutation *LinkCategoryMutation
	hooks    []Hook
	conflict []sql.ConflictOption
}

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

// SetDescription sets the "description" field.
func (_c *LinkCategoryCreate) SetDescription(v string) *LinkCategoryCreate {
	_c.mutation.SetDescription(v)
	return _c
}

// SetNillableDescription sets the "description" field if the given value is not nil.
func (_c *LinkCategoryCreate) SetNillableDescription(v *string) *LinkCategoryCreate {
	if v != nil {
		_c.SetDescription(*v)
	}
	return _c
}

// SetStyle sets the "style" field.
func (_c *LinkCategoryCreate) SetStyle(v linkcategory.Style) *LinkCategoryCreate {
	_c.mutation.SetStyle(v)
	return _c
}

// SetNillableStyle sets the "style" field if the given value is not nil.
func (_c *LinkCategoryCreate) SetNillableStyle(v *linkcategory.Style) *LinkCategoryCreate {
	if v != nil {
		_c.SetStyle(*v)
	}
	return _c
}

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

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

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

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

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

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

// ExecX is like Exec, but panics if an error occurs.
func (_c *LinkCategoryCreate) 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 *LinkCategoryCreate) defaults() {
	if _, ok := _c.mutation.Style(); !ok {
		v := linkcategory.DefaultStyle
		_c.mutation.SetStyle(v)
	}
}

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

func (_c *LinkCategoryCreate) sqlSave(ctx context.Context) (*LinkCategory, 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 *LinkCategoryCreate) createSpec() (*LinkCategory, *sqlgraph.CreateSpec) {
	var (
		_node = &LinkCategory{config: _c.config}
		_spec = sqlgraph.NewCreateSpec(linkcategory.Table, sqlgraph.NewFieldSpec(linkcategory.FieldID, field.TypeInt))
	)
	_spec.OnConflict = _c.conflict
	if value, ok := _c.mutation.Name(); ok {
		_spec.SetField(linkcategory.FieldName, field.TypeString, value)
		_node.Name = value
	}
	if value, ok := _c.mutation.Description(); ok {
		_spec.SetField(linkcategory.FieldDescription, field.TypeString, value)
		_node.Description = value
	}
	if value, ok := _c.mutation.Style(); ok {
		_spec.SetField(linkcategory.FieldStyle, field.TypeEnum, value)
		_node.Style = value
	}
	if nodes := _c.mutation.LinksIDs(); len(nodes) > 0 {
		edge := &sqlgraph.EdgeSpec{
			Rel:     sqlgraph.O2M,
			Inverse: false,
			Table:   linkcategory.LinksTable,
			Columns: []string{linkcategory.LinksColumn},
			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.LinkCategory.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.LinkCategoryUpsert) {
//			SetName(v+v).
//		}).
//		Exec(ctx)
func (_c *LinkCategoryCreate) OnConflict(opts ...sql.ConflictOption) *LinkCategoryUpsertOne {
	_c.conflict = opts
	return &LinkCategoryUpsertOne{
		create: _c,
	}
}

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

type (
	// LinkCategoryUpsertOne is the builder for "upsert"-ing
	//  one LinkCategory node.
	LinkCategoryUpsertOne struct {
		create *LinkCategoryCreate
	}

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

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

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

// SetDescription sets the "description" field.
func (u *LinkCategoryUpsert) SetDescription(v string) *LinkCategoryUpsert {
	u.Set(linkcategory.FieldDescription, v)
	return u
}

// UpdateDescription sets the "description" field to the value that was provided on create.
func (u *LinkCategoryUpsert) UpdateDescription() *LinkCategoryUpsert {
	u.SetExcluded(linkcategory.FieldDescription)
	return u
}

// ClearDescription clears the value of the "description" field.
func (u *LinkCategoryUpsert) ClearDescription() *LinkCategoryUpsert {
	u.SetNull(linkcategory.FieldDescription)
	return u
}

// SetStyle sets the "style" field.
func (u *LinkCategoryUpsert) SetStyle(v linkcategory.Style) *LinkCategoryUpsert {
	u.Set(linkcategory.FieldStyle, v)
	return u
}

// UpdateStyle sets the "style" field to the value that was provided on create.
func (u *LinkCategoryUpsert) UpdateStyle() *LinkCategoryUpsert {
	u.SetExcluded(linkcategory.FieldStyle)
	return u
}

// UpdateNewValues updates the mutable fields using the new values that were set on create.
// Using this option is equivalent to using:
//
//	client.LinkCategory.Create().
//		OnConflict(
//			sql.ResolveWithNewValues(),
//		).
//		Exec(ctx)
func (u *LinkCategoryUpsertOne) UpdateNewValues() *LinkCategoryUpsertOne {
	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.LinkCategory.Create().
//	    OnConflict(sql.ResolveWithIgnore()).
//	    Exec(ctx)
func (u *LinkCategoryUpsertOne) Ignore() *LinkCategoryUpsertOne {
	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 *LinkCategoryUpsertOne) DoNothing() *LinkCategoryUpsertOne {
	u.create.conflict = append(u.create.conflict, sql.DoNothing())
	return u
}

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

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

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

// SetDescription sets the "description" field.
func (u *LinkCategoryUpsertOne) SetDescription(v string) *LinkCategoryUpsertOne {
	return u.Update(func(s *LinkCategoryUpsert) {
		s.SetDescription(v)
	})
}

// UpdateDescription sets the "description" field to the value that was provided on create.
func (u *LinkCategoryUpsertOne) UpdateDescription() *LinkCategoryUpsertOne {
	return u.Update(func(s *LinkCategoryUpsert) {
		s.UpdateDescription()
	})
}

// ClearDescription clears the value of the "description" field.
func (u *LinkCategoryUpsertOne) ClearDescription() *LinkCategoryUpsertOne {
	return u.Update(func(s *LinkCategoryUpsert) {
		s.ClearDescription()
	})
}

// SetStyle sets the "style" field.
func (u *LinkCategoryUpsertOne) SetStyle(v linkcategory.Style) *LinkCategoryUpsertOne {
	return u.Update(func(s *LinkCategoryUpsert) {
		s.SetStyle(v)
	})
}

// UpdateStyle sets the "style" field to the value that was provided on create.
func (u *LinkCategoryUpsertOne) UpdateStyle() *LinkCategoryUpsertOne {
	return u.Update(func(s *LinkCategoryUpsert) {
		s.UpdateStyle()
	})
}

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

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

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

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

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

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

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

// LinkCategoryUpsertBulk is the builder for "upsert"-ing
// a bulk of LinkCategory nodes.
type LinkCategoryUpsertBulk struct {
	create *LinkCategoryCreateBulk
}

// UpdateNewValues updates the mutable fields using the new values that
// were set on create. Using this option is equivalent to using:
//
//	client.LinkCategory.Create().
//		OnConflict(
//			sql.ResolveWithNewValues(),
//		).
//		Exec(ctx)
func (u *LinkCategoryUpsertBulk) UpdateNewValues() *LinkCategoryUpsertBulk {
	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.LinkCategory.Create().
//		OnConflict(sql.ResolveWithIgnore()).
//		Exec(ctx)
func (u *LinkCategoryUpsertBulk) Ignore() *LinkCategoryUpsertBulk {
	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 *LinkCategoryUpsertBulk) DoNothing() *LinkCategoryUpsertBulk {
	u.create.conflict = append(u.create.conflict, sql.DoNothing())
	return u
}

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

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

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

// SetDescription sets the "description" field.
func (u *LinkCategoryUpsertBulk) SetDescription(v string) *LinkCategoryUpsertBulk {
	return u.Update(func(s *LinkCategoryUpsert) {
		s.SetDescription(v)
	})
}

// UpdateDescription sets the "description" field to the value that was provided on create.
func (u *LinkCategoryUpsertBulk) UpdateDescription() *LinkCategoryUpsertBulk {
	return u.Update(func(s *LinkCategoryUpsert) {
		s.UpdateDescription()
	})
}

// ClearDescription clears the value of the "description" field.
func (u *LinkCategoryUpsertBulk) ClearDescription() *LinkCategoryUpsertBulk {
	return u.Update(func(s *LinkCategoryUpsert) {
		s.ClearDescription()
	})
}

// SetStyle sets the "style" field.
func (u *LinkCategoryUpsertBulk) SetStyle(v linkcategory.Style) *LinkCategoryUpsertBulk {
	return u.Update(func(s *LinkCategoryUpsert) {
		s.SetStyle(v)
	})
}

// UpdateStyle sets the "style" field to the value that was provided on create.
func (u *LinkCategoryUpsertBulk) UpdateStyle() *LinkCategoryUpsertBulk {
	return u.Update(func(s *LinkCategoryUpsert) {
		s.UpdateStyle()
	})
}

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

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