// 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/anzhiyu-c/anheyu-app/ent/article"
	"github.com/anzhiyu-c/anheyu-app/ent/posttag"
	"github.com/anzhiyu-c/anheyu-app/ent/predicate"
)

// PostTagUpdate is the builder for updating PostTag entities.
type PostTagUpdate struct {
	config
	hooks     []Hook
	mutation  *PostTagMutation
	modifiers []func(*sql.UpdateBuilder)
}

// Where appends a list predicates to the PostTagUpdate builder.
func (_u *PostTagUpdate) Where(ps ...predicate.PostTag) *PostTagUpdate {
	_u.mutation.Where(ps...)
	return _u
}

// SetDeletedAt sets the "deleted_at" field.
func (_u *PostTagUpdate) SetDeletedAt(v time.Time) *PostTagUpdate {
	_u.mutation.SetDeletedAt(v)
	return _u
}

// SetNillableDeletedAt sets the "deleted_at" field if the given value is not nil.
func (_u *PostTagUpdate) SetNillableDeletedAt(v *time.Time) *PostTagUpdate {
	if v != nil {
		_u.SetDeletedAt(*v)
	}
	return _u
}

// ClearDeletedAt clears the value of the "deleted_at" field.
func (_u *PostTagUpdate) ClearDeletedAt() *PostTagUpdate {
	_u.mutation.ClearDeletedAt()
	return _u
}

// SetUpdatedAt sets the "updated_at" field.
func (_u *PostTagUpdate) SetUpdatedAt(v time.Time) *PostTagUpdate {
	_u.mutation.SetUpdatedAt(v)
	return _u
}

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

// SetNillableName sets the "name" field if the given value is not nil.
func (_u *PostTagUpdate) SetNillableName(v *string) *PostTagUpdate {
	if v != nil {
		_u.SetName(*v)
	}
	return _u
}

// SetCount sets the "count" field.
func (_u *PostTagUpdate) SetCount(v int) *PostTagUpdate {
	_u.mutation.ResetCount()
	_u.mutation.SetCount(v)
	return _u
}

// SetNillableCount sets the "count" field if the given value is not nil.
func (_u *PostTagUpdate) SetNillableCount(v *int) *PostTagUpdate {
	if v != nil {
		_u.SetCount(*v)
	}
	return _u
}

// AddCount adds value to the "count" field.
func (_u *PostTagUpdate) AddCount(v int) *PostTagUpdate {
	_u.mutation.AddCount(v)
	return _u
}

// AddArticleIDs adds the "articles" edge to the Article entity by IDs.
func (_u *PostTagUpdate) AddArticleIDs(ids ...uint) *PostTagUpdate {
	_u.mutation.AddArticleIDs(ids...)
	return _u
}

// AddArticles adds the "articles" edges to the Article entity.
func (_u *PostTagUpdate) AddArticles(v ...*Article) *PostTagUpdate {
	ids := make([]uint, len(v))
	for i := range v {
		ids[i] = v[i].ID
	}
	return _u.AddArticleIDs(ids...)
}

// Mutation returns the PostTagMutation object of the builder.
func (_u *PostTagUpdate) Mutation() *PostTagMutation {
	return _u.mutation
}

// ClearArticles clears all "articles" edges to the Article entity.
func (_u *PostTagUpdate) ClearArticles() *PostTagUpdate {
	_u.mutation.ClearArticles()
	return _u
}

// RemoveArticleIDs removes the "articles" edge to Article entities by IDs.
func (_u *PostTagUpdate) RemoveArticleIDs(ids ...uint) *PostTagUpdate {
	_u.mutation.RemoveArticleIDs(ids...)
	return _u
}

// RemoveArticles removes "articles" edges to Article entities.
func (_u *PostTagUpdate) RemoveArticles(v ...*Article) *PostTagUpdate {
	ids := make([]uint, len(v))
	for i := range v {
		ids[i] = v[i].ID
	}
	return _u.RemoveArticleIDs(ids...)
}

// Save executes the query and returns the number of nodes affected by the update operation.
func (_u *PostTagUpdate) Save(ctx context.Context) (int, error) {
	if err := _u.defaults(); err != nil {
		return 0, err
	}
	return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks)
}

// SaveX is like Save, but panics if an error occurs.
func (_u *PostTagUpdate) SaveX(ctx context.Context) int {
	affected, err := _u.Save(ctx)
	if err != nil {
		panic(err)
	}
	return affected
}

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

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

// defaults sets the default values of the builder before save.
func (_u *PostTagUpdate) defaults() error {
	if _, ok := _u.mutation.UpdatedAt(); !ok {
		if posttag.UpdateDefaultUpdatedAt == nil {
			return fmt.Errorf("ent: uninitialized posttag.UpdateDefaultUpdatedAt (forgotten import ent/runtime?)")
		}
		v := posttag.UpdateDefaultUpdatedAt()
		_u.mutation.SetUpdatedAt(v)
	}
	return nil
}

// check runs all checks and user-defined validators on the builder.
func (_u *PostTagUpdate) check() error {
	if v, ok := _u.mutation.Name(); ok {
		if err := posttag.NameValidator(v); err != nil {
			return &ValidationError{Name: "name", err: fmt.Errorf(`ent: validator failed for field "PostTag.name": %w`, err)}
		}
	}
	if v, ok := _u.mutation.Count(); ok {
		if err := posttag.CountValidator(v); err != nil {
			return &ValidationError{Name: "count", err: fmt.Errorf(`ent: validator failed for field "PostTag.count": %w`, err)}
		}
	}
	return nil
}

// Modify adds a statement modifier for attaching custom logic to the UPDATE statement.
func (_u *PostTagUpdate) Modify(modifiers ...func(u *sql.UpdateBuilder)) *PostTagUpdate {
	_u.modifiers = append(_u.modifiers, modifiers...)
	return _u
}

func (_u *PostTagUpdate) sqlSave(ctx context.Context) (_node int, err error) {
	if err := _u.check(); err != nil {
		return _node, err
	}
	_spec := sqlgraph.NewUpdateSpec(posttag.Table, posttag.Columns, sqlgraph.NewFieldSpec(posttag.FieldID, field.TypeUint))
	if ps := _u.mutation.predicates; len(ps) > 0 {
		_spec.Predicate = func(selector *sql.Selector) {
			for i := range ps {
				ps[i](selector)
			}
		}
	}
	if value, ok := _u.mutation.DeletedAt(); ok {
		_spec.SetField(posttag.FieldDeletedAt, field.TypeTime, value)
	}
	if _u.mutation.DeletedAtCleared() {
		_spec.ClearField(posttag.FieldDeletedAt, field.TypeTime)
	}
	if value, ok := _u.mutation.UpdatedAt(); ok {
		_spec.SetField(posttag.FieldUpdatedAt, field.TypeTime, value)
	}
	if value, ok := _u.mutation.Name(); ok {
		_spec.SetField(posttag.FieldName, field.TypeString, value)
	}
	if value, ok := _u.mutation.Count(); ok {
		_spec.SetField(posttag.FieldCount, field.TypeInt, value)
	}
	if value, ok := _u.mutation.AddedCount(); ok {
		_spec.AddField(posttag.FieldCount, field.TypeInt, value)
	}
	if _u.mutation.ArticlesCleared() {
		edge := &sqlgraph.EdgeSpec{
			Rel:     sqlgraph.M2M,
			Inverse: true,
			Table:   posttag.ArticlesTable,
			Columns: posttag.ArticlesPrimaryKey,
			Bidi:    false,
			Target: &sqlgraph.EdgeTarget{
				IDSpec: sqlgraph.NewFieldSpec(article.FieldID, field.TypeUint),
			},
		}
		_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
	}
	if nodes := _u.mutation.RemovedArticlesIDs(); len(nodes) > 0 && !_u.mutation.ArticlesCleared() {
		edge := &sqlgraph.EdgeSpec{
			Rel:     sqlgraph.M2M,
			Inverse: true,
			Table:   posttag.ArticlesTable,
			Columns: posttag.ArticlesPrimaryKey,
			Bidi:    false,
			Target: &sqlgraph.EdgeTarget{
				IDSpec: sqlgraph.NewFieldSpec(article.FieldID, field.TypeUint),
			},
		}
		for _, k := range nodes {
			edge.Target.Nodes = append(edge.Target.Nodes, k)
		}
		_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
	}
	if nodes := _u.mutation.ArticlesIDs(); len(nodes) > 0 {
		edge := &sqlgraph.EdgeSpec{
			Rel:     sqlgraph.M2M,
			Inverse: true,
			Table:   posttag.ArticlesTable,
			Columns: posttag.ArticlesPrimaryKey,
			Bidi:    false,
			Target: &sqlgraph.EdgeTarget{
				IDSpec: sqlgraph.NewFieldSpec(article.FieldID, field.TypeUint),
			},
		}
		for _, k := range nodes {
			edge.Target.Nodes = append(edge.Target.Nodes, k)
		}
		_spec.Edges.Add = append(_spec.Edges.Add, edge)
	}
	_spec.AddModifiers(_u.modifiers...)
	if _node, err = sqlgraph.UpdateNodes(ctx, _u.driver, _spec); err != nil {
		if _, ok := err.(*sqlgraph.NotFoundError); ok {
			err = &NotFoundError{posttag.Label}
		} else if sqlgraph.IsConstraintError(err) {
			err = &ConstraintError{msg: err.Error(), wrap: err}
		}
		return 0, err
	}
	_u.mutation.done = true
	return _node, nil
}

// PostTagUpdateOne is the builder for updating a single PostTag entity.
type PostTagUpdateOne struct {
	config
	fields    []string
	hooks     []Hook
	mutation  *PostTagMutation
	modifiers []func(*sql.UpdateBuilder)
}

// SetDeletedAt sets the "deleted_at" field.
func (_u *PostTagUpdateOne) SetDeletedAt(v time.Time) *PostTagUpdateOne {
	_u.mutation.SetDeletedAt(v)
	return _u
}

// SetNillableDeletedAt sets the "deleted_at" field if the given value is not nil.
func (_u *PostTagUpdateOne) SetNillableDeletedAt(v *time.Time) *PostTagUpdateOne {
	if v != nil {
		_u.SetDeletedAt(*v)
	}
	return _u
}

// ClearDeletedAt clears the value of the "deleted_at" field.
func (_u *PostTagUpdateOne) ClearDeletedAt() *PostTagUpdateOne {
	_u.mutation.ClearDeletedAt()
	return _u
}

// SetUpdatedAt sets the "updated_at" field.
func (_u *PostTagUpdateOne) SetUpdatedAt(v time.Time) *PostTagUpdateOne {
	_u.mutation.SetUpdatedAt(v)
	return _u
}

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

// SetNillableName sets the "name" field if the given value is not nil.
func (_u *PostTagUpdateOne) SetNillableName(v *string) *PostTagUpdateOne {
	if v != nil {
		_u.SetName(*v)
	}
	return _u
}

// SetCount sets the "count" field.
func (_u *PostTagUpdateOne) SetCount(v int) *PostTagUpdateOne {
	_u.mutation.ResetCount()
	_u.mutation.SetCount(v)
	return _u
}

// SetNillableCount sets the "count" field if the given value is not nil.
func (_u *PostTagUpdateOne) SetNillableCount(v *int) *PostTagUpdateOne {
	if v != nil {
		_u.SetCount(*v)
	}
	return _u
}

// AddCount adds value to the "count" field.
func (_u *PostTagUpdateOne) AddCount(v int) *PostTagUpdateOne {
	_u.mutation.AddCount(v)
	return _u
}

// AddArticleIDs adds the "articles" edge to the Article entity by IDs.
func (_u *PostTagUpdateOne) AddArticleIDs(ids ...uint) *PostTagUpdateOne {
	_u.mutation.AddArticleIDs(ids...)
	return _u
}

// AddArticles adds the "articles" edges to the Article entity.
func (_u *PostTagUpdateOne) AddArticles(v ...*Article) *PostTagUpdateOne {
	ids := make([]uint, len(v))
	for i := range v {
		ids[i] = v[i].ID
	}
	return _u.AddArticleIDs(ids...)
}

// Mutation returns the PostTagMutation object of the builder.
func (_u *PostTagUpdateOne) Mutation() *PostTagMutation {
	return _u.mutation
}

// ClearArticles clears all "articles" edges to the Article entity.
func (_u *PostTagUpdateOne) ClearArticles() *PostTagUpdateOne {
	_u.mutation.ClearArticles()
	return _u
}

// RemoveArticleIDs removes the "articles" edge to Article entities by IDs.
func (_u *PostTagUpdateOne) RemoveArticleIDs(ids ...uint) *PostTagUpdateOne {
	_u.mutation.RemoveArticleIDs(ids...)
	return _u
}

// RemoveArticles removes "articles" edges to Article entities.
func (_u *PostTagUpdateOne) RemoveArticles(v ...*Article) *PostTagUpdateOne {
	ids := make([]uint, len(v))
	for i := range v {
		ids[i] = v[i].ID
	}
	return _u.RemoveArticleIDs(ids...)
}

// Where appends a list predicates to the PostTagUpdate builder.
func (_u *PostTagUpdateOne) Where(ps ...predicate.PostTag) *PostTagUpdateOne {
	_u.mutation.Where(ps...)
	return _u
}

// Select allows selecting one or more fields (columns) of the returned entity.
// The default is selecting all fields defined in the entity schema.
func (_u *PostTagUpdateOne) Select(field string, fields ...string) *PostTagUpdateOne {
	_u.fields = append([]string{field}, fields...)
	return _u
}

// Save executes the query and returns the updated PostTag entity.
func (_u *PostTagUpdateOne) Save(ctx context.Context) (*PostTag, error) {
	if err := _u.defaults(); err != nil {
		return nil, err
	}
	return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks)
}

// SaveX is like Save, but panics if an error occurs.
func (_u *PostTagUpdateOne) SaveX(ctx context.Context) *PostTag {
	node, err := _u.Save(ctx)
	if err != nil {
		panic(err)
	}
	return node
}

// Exec executes the query on the entity.
func (_u *PostTagUpdateOne) Exec(ctx context.Context) error {
	_, err := _u.Save(ctx)
	return err
}

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

// defaults sets the default values of the builder before save.
func (_u *PostTagUpdateOne) defaults() error {
	if _, ok := _u.mutation.UpdatedAt(); !ok {
		if posttag.UpdateDefaultUpdatedAt == nil {
			return fmt.Errorf("ent: uninitialized posttag.UpdateDefaultUpdatedAt (forgotten import ent/runtime?)")
		}
		v := posttag.UpdateDefaultUpdatedAt()
		_u.mutation.SetUpdatedAt(v)
	}
	return nil
}

// check runs all checks and user-defined validators on the builder.
func (_u *PostTagUpdateOne) check() error {
	if v, ok := _u.mutation.Name(); ok {
		if err := posttag.NameValidator(v); err != nil {
			return &ValidationError{Name: "name", err: fmt.Errorf(`ent: validator failed for field "PostTag.name": %w`, err)}
		}
	}
	if v, ok := _u.mutation.Count(); ok {
		if err := posttag.CountValidator(v); err != nil {
			return &ValidationError{Name: "count", err: fmt.Errorf(`ent: validator failed for field "PostTag.count": %w`, err)}
		}
	}
	return nil
}

// Modify adds a statement modifier for attaching custom logic to the UPDATE statement.
func (_u *PostTagUpdateOne) Modify(modifiers ...func(u *sql.UpdateBuilder)) *PostTagUpdateOne {
	_u.modifiers = append(_u.modifiers, modifiers...)
	return _u
}

func (_u *PostTagUpdateOne) sqlSave(ctx context.Context) (_node *PostTag, err error) {
	if err := _u.check(); err != nil {
		return _node, err
	}
	_spec := sqlgraph.NewUpdateSpec(posttag.Table, posttag.Columns, sqlgraph.NewFieldSpec(posttag.FieldID, field.TypeUint))
	id, ok := _u.mutation.ID()
	if !ok {
		return nil, &ValidationError{Name: "id", err: errors.New(`ent: missing "PostTag.id" for update`)}
	}
	_spec.Node.ID.Value = id
	if fields := _u.fields; len(fields) > 0 {
		_spec.Node.Columns = make([]string, 0, len(fields))
		_spec.Node.Columns = append(_spec.Node.Columns, posttag.FieldID)
		for _, f := range fields {
			if !posttag.ValidColumn(f) {
				return nil, &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)}
			}
			if f != posttag.FieldID {
				_spec.Node.Columns = append(_spec.Node.Columns, f)
			}
		}
	}
	if ps := _u.mutation.predicates; len(ps) > 0 {
		_spec.Predicate = func(selector *sql.Selector) {
			for i := range ps {
				ps[i](selector)
			}
		}
	}
	if value, ok := _u.mutation.DeletedAt(); ok {
		_spec.SetField(posttag.FieldDeletedAt, field.TypeTime, value)
	}
	if _u.mutation.DeletedAtCleared() {
		_spec.ClearField(posttag.FieldDeletedAt, field.TypeTime)
	}
	if value, ok := _u.mutation.UpdatedAt(); ok {
		_spec.SetField(posttag.FieldUpdatedAt, field.TypeTime, value)
	}
	if value, ok := _u.mutation.Name(); ok {
		_spec.SetField(posttag.FieldName, field.TypeString, value)
	}
	if value, ok := _u.mutation.Count(); ok {
		_spec.SetField(posttag.FieldCount, field.TypeInt, value)
	}
	if value, ok := _u.mutation.AddedCount(); ok {
		_spec.AddField(posttag.FieldCount, field.TypeInt, value)
	}
	if _u.mutation.ArticlesCleared() {
		edge := &sqlgraph.EdgeSpec{
			Rel:     sqlgraph.M2M,
			Inverse: true,
			Table:   posttag.ArticlesTable,
			Columns: posttag.ArticlesPrimaryKey,
			Bidi:    false,
			Target: &sqlgraph.EdgeTarget{
				IDSpec: sqlgraph.NewFieldSpec(article.FieldID, field.TypeUint),
			},
		}
		_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
	}
	if nodes := _u.mutation.RemovedArticlesIDs(); len(nodes) > 0 && !_u.mutation.ArticlesCleared() {
		edge := &sqlgraph.EdgeSpec{
			Rel:     sqlgraph.M2M,
			Inverse: true,
			Table:   posttag.ArticlesTable,
			Columns: posttag.ArticlesPrimaryKey,
			Bidi:    false,
			Target: &sqlgraph.EdgeTarget{
				IDSpec: sqlgraph.NewFieldSpec(article.FieldID, field.TypeUint),
			},
		}
		for _, k := range nodes {
			edge.Target.Nodes = append(edge.Target.Nodes, k)
		}
		_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
	}
	if nodes := _u.mutation.ArticlesIDs(); len(nodes) > 0 {
		edge := &sqlgraph.EdgeSpec{
			Rel:     sqlgraph.M2M,
			Inverse: true,
			Table:   posttag.ArticlesTable,
			Columns: posttag.ArticlesPrimaryKey,
			Bidi:    false,
			Target: &sqlgraph.EdgeTarget{
				IDSpec: sqlgraph.NewFieldSpec(article.FieldID, field.TypeUint),
			},
		}
		for _, k := range nodes {
			edge.Target.Nodes = append(edge.Target.Nodes, k)
		}
		_spec.Edges.Add = append(_spec.Edges.Add, edge)
	}
	_spec.AddModifiers(_u.modifiers...)
	_node = &PostTag{config: _u.config}
	_spec.Assign = _node.assignValues
	_spec.ScanValues = _node.scanValues
	if err = sqlgraph.UpdateNode(ctx, _u.driver, _spec); err != nil {
		if _, ok := err.(*sqlgraph.NotFoundError); ok {
			err = &NotFoundError{posttag.Label}
		} else if sqlgraph.IsConstraintError(err) {
			err = &ConstraintError{msg: err.Error(), wrap: err}
		}
		return nil, err
	}
	_u.mutation.done = true
	return _node, nil
}
