// 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/crowdsecurity/crowdsec/pkg/database/ent/alert"
	"github.com/crowdsecurity/crowdsec/pkg/database/ent/meta"
	"github.com/crowdsecurity/crowdsec/pkg/database/ent/predicate"
)

// MetaUpdate is the builder for updating Meta entities.
type MetaUpdate struct {
	config
	hooks    []Hook
	mutation *MetaMutation
}

// Where appends a list predicates to the MetaUpdate builder.
func (mu *MetaUpdate) Where(ps ...predicate.Meta) *MetaUpdate {
	mu.mutation.Where(ps...)
	return mu
}

// SetCreatedAt sets the "created_at" field.
func (mu *MetaUpdate) SetCreatedAt(t time.Time) *MetaUpdate {
	mu.mutation.SetCreatedAt(t)
	return mu
}

// ClearCreatedAt clears the value of the "created_at" field.
func (mu *MetaUpdate) ClearCreatedAt() *MetaUpdate {
	mu.mutation.ClearCreatedAt()
	return mu
}

// SetUpdatedAt sets the "updated_at" field.
func (mu *MetaUpdate) SetUpdatedAt(t time.Time) *MetaUpdate {
	mu.mutation.SetUpdatedAt(t)
	return mu
}

// ClearUpdatedAt clears the value of the "updated_at" field.
func (mu *MetaUpdate) ClearUpdatedAt() *MetaUpdate {
	mu.mutation.ClearUpdatedAt()
	return mu
}

// SetKey sets the "key" field.
func (mu *MetaUpdate) SetKey(s string) *MetaUpdate {
	mu.mutation.SetKey(s)
	return mu
}

// SetValue sets the "value" field.
func (mu *MetaUpdate) SetValue(s string) *MetaUpdate {
	mu.mutation.SetValue(s)
	return mu
}

// SetOwnerID sets the "owner" edge to the Alert entity by ID.
func (mu *MetaUpdate) SetOwnerID(id int) *MetaUpdate {
	mu.mutation.SetOwnerID(id)
	return mu
}

// SetNillableOwnerID sets the "owner" edge to the Alert entity by ID if the given value is not nil.
func (mu *MetaUpdate) SetNillableOwnerID(id *int) *MetaUpdate {
	if id != nil {
		mu = mu.SetOwnerID(*id)
	}
	return mu
}

// SetOwner sets the "owner" edge to the Alert entity.
func (mu *MetaUpdate) SetOwner(a *Alert) *MetaUpdate {
	return mu.SetOwnerID(a.ID)
}

// Mutation returns the MetaMutation object of the builder.
func (mu *MetaUpdate) Mutation() *MetaMutation {
	return mu.mutation
}

// ClearOwner clears the "owner" edge to the Alert entity.
func (mu *MetaUpdate) ClearOwner() *MetaUpdate {
	mu.mutation.ClearOwner()
	return mu
}

// Save executes the query and returns the number of nodes affected by the update operation.
func (mu *MetaUpdate) Save(ctx context.Context) (int, error) {
	var (
		err      error
		affected int
	)
	mu.defaults()
	if len(mu.hooks) == 0 {
		if err = mu.check(); err != nil {
			return 0, err
		}
		affected, err = mu.sqlSave(ctx)
	} else {
		var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
			mutation, ok := m.(*MetaMutation)
			if !ok {
				return nil, fmt.Errorf("unexpected mutation type %T", m)
			}
			if err = mu.check(); err != nil {
				return 0, err
			}
			mu.mutation = mutation
			affected, err = mu.sqlSave(ctx)
			mutation.done = true
			return affected, err
		})
		for i := len(mu.hooks) - 1; i >= 0; i-- {
			if mu.hooks[i] == nil {
				return 0, fmt.Errorf("ent: uninitialized hook (forgotten import ent/runtime?)")
			}
			mut = mu.hooks[i](mut)
		}
		if _, err := mut.Mutate(ctx, mu.mutation); err != nil {
			return 0, err
		}
	}
	return affected, err
}

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

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

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

// defaults sets the default values of the builder before save.
func (mu *MetaUpdate) defaults() {
	if _, ok := mu.mutation.CreatedAt(); !ok && !mu.mutation.CreatedAtCleared() {
		v := meta.UpdateDefaultCreatedAt()
		mu.mutation.SetCreatedAt(v)
	}
	if _, ok := mu.mutation.UpdatedAt(); !ok && !mu.mutation.UpdatedAtCleared() {
		v := meta.UpdateDefaultUpdatedAt()
		mu.mutation.SetUpdatedAt(v)
	}
}

// check runs all checks and user-defined validators on the builder.
func (mu *MetaUpdate) check() error {
	if v, ok := mu.mutation.Value(); ok {
		if err := meta.ValueValidator(v); err != nil {
			return &ValidationError{Name: "value", err: fmt.Errorf(`ent: validator failed for field "Meta.value": %w`, err)}
		}
	}
	return nil
}

func (mu *MetaUpdate) sqlSave(ctx context.Context) (n int, err error) {
	_spec := &sqlgraph.UpdateSpec{
		Node: &sqlgraph.NodeSpec{
			Table:   meta.Table,
			Columns: meta.Columns,
			ID: &sqlgraph.FieldSpec{
				Type:   field.TypeInt,
				Column: meta.FieldID,
			},
		},
	}
	if ps := mu.mutation.predicates; len(ps) > 0 {
		_spec.Predicate = func(selector *sql.Selector) {
			for i := range ps {
				ps[i](selector)
			}
		}
	}
	if value, ok := mu.mutation.CreatedAt(); ok {
		_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
			Type:   field.TypeTime,
			Value:  value,
			Column: meta.FieldCreatedAt,
		})
	}
	if mu.mutation.CreatedAtCleared() {
		_spec.Fields.Clear = append(_spec.Fields.Clear, &sqlgraph.FieldSpec{
			Type:   field.TypeTime,
			Column: meta.FieldCreatedAt,
		})
	}
	if value, ok := mu.mutation.UpdatedAt(); ok {
		_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
			Type:   field.TypeTime,
			Value:  value,
			Column: meta.FieldUpdatedAt,
		})
	}
	if mu.mutation.UpdatedAtCleared() {
		_spec.Fields.Clear = append(_spec.Fields.Clear, &sqlgraph.FieldSpec{
			Type:   field.TypeTime,
			Column: meta.FieldUpdatedAt,
		})
	}
	if value, ok := mu.mutation.Key(); ok {
		_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
			Type:   field.TypeString,
			Value:  value,
			Column: meta.FieldKey,
		})
	}
	if value, ok := mu.mutation.Value(); ok {
		_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
			Type:   field.TypeString,
			Value:  value,
			Column: meta.FieldValue,
		})
	}
	if mu.mutation.OwnerCleared() {
		edge := &sqlgraph.EdgeSpec{
			Rel:     sqlgraph.M2O,
			Inverse: true,
			Table:   meta.OwnerTable,
			Columns: []string{meta.OwnerColumn},
			Bidi:    false,
			Target: &sqlgraph.EdgeTarget{
				IDSpec: &sqlgraph.FieldSpec{
					Type:   field.TypeInt,
					Column: alert.FieldID,
				},
			},
		}
		_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
	}
	if nodes := mu.mutation.OwnerIDs(); len(nodes) > 0 {
		edge := &sqlgraph.EdgeSpec{
			Rel:     sqlgraph.M2O,
			Inverse: true,
			Table:   meta.OwnerTable,
			Columns: []string{meta.OwnerColumn},
			Bidi:    false,
			Target: &sqlgraph.EdgeTarget{
				IDSpec: &sqlgraph.FieldSpec{
					Type:   field.TypeInt,
					Column: alert.FieldID,
				},
			},
		}
		for _, k := range nodes {
			edge.Target.Nodes = append(edge.Target.Nodes, k)
		}
		_spec.Edges.Add = append(_spec.Edges.Add, edge)
	}
	if n, err = sqlgraph.UpdateNodes(ctx, mu.driver, _spec); err != nil {
		if _, ok := err.(*sqlgraph.NotFoundError); ok {
			err = &NotFoundError{meta.Label}
		} else if sqlgraph.IsConstraintError(err) {
			err = &ConstraintError{msg: err.Error(), wrap: err}
		}
		return 0, err
	}
	return n, nil
}

// MetaUpdateOne is the builder for updating a single Meta entity.
type MetaUpdateOne struct {
	config
	fields   []string
	hooks    []Hook
	mutation *MetaMutation
}

// SetCreatedAt sets the "created_at" field.
func (muo *MetaUpdateOne) SetCreatedAt(t time.Time) *MetaUpdateOne {
	muo.mutation.SetCreatedAt(t)
	return muo
}

// ClearCreatedAt clears the value of the "created_at" field.
func (muo *MetaUpdateOne) ClearCreatedAt() *MetaUpdateOne {
	muo.mutation.ClearCreatedAt()
	return muo
}

// SetUpdatedAt sets the "updated_at" field.
func (muo *MetaUpdateOne) SetUpdatedAt(t time.Time) *MetaUpdateOne {
	muo.mutation.SetUpdatedAt(t)
	return muo
}

// ClearUpdatedAt clears the value of the "updated_at" field.
func (muo *MetaUpdateOne) ClearUpdatedAt() *MetaUpdateOne {
	muo.mutation.ClearUpdatedAt()
	return muo
}

// SetKey sets the "key" field.
func (muo *MetaUpdateOne) SetKey(s string) *MetaUpdateOne {
	muo.mutation.SetKey(s)
	return muo
}

// SetValue sets the "value" field.
func (muo *MetaUpdateOne) SetValue(s string) *MetaUpdateOne {
	muo.mutation.SetValue(s)
	return muo
}

// SetOwnerID sets the "owner" edge to the Alert entity by ID.
func (muo *MetaUpdateOne) SetOwnerID(id int) *MetaUpdateOne {
	muo.mutation.SetOwnerID(id)
	return muo
}

// SetNillableOwnerID sets the "owner" edge to the Alert entity by ID if the given value is not nil.
func (muo *MetaUpdateOne) SetNillableOwnerID(id *int) *MetaUpdateOne {
	if id != nil {
		muo = muo.SetOwnerID(*id)
	}
	return muo
}

// SetOwner sets the "owner" edge to the Alert entity.
func (muo *MetaUpdateOne) SetOwner(a *Alert) *MetaUpdateOne {
	return muo.SetOwnerID(a.ID)
}

// Mutation returns the MetaMutation object of the builder.
func (muo *MetaUpdateOne) Mutation() *MetaMutation {
	return muo.mutation
}

// ClearOwner clears the "owner" edge to the Alert entity.
func (muo *MetaUpdateOne) ClearOwner() *MetaUpdateOne {
	muo.mutation.ClearOwner()
	return muo
}

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

// Save executes the query and returns the updated Meta entity.
func (muo *MetaUpdateOne) Save(ctx context.Context) (*Meta, error) {
	var (
		err  error
		node *Meta
	)
	muo.defaults()
	if len(muo.hooks) == 0 {
		if err = muo.check(); err != nil {
			return nil, err
		}
		node, err = muo.sqlSave(ctx)
	} else {
		var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
			mutation, ok := m.(*MetaMutation)
			if !ok {
				return nil, fmt.Errorf("unexpected mutation type %T", m)
			}
			if err = muo.check(); err != nil {
				return nil, err
			}
			muo.mutation = mutation
			node, err = muo.sqlSave(ctx)
			mutation.done = true
			return node, err
		})
		for i := len(muo.hooks) - 1; i >= 0; i-- {
			if muo.hooks[i] == nil {
				return nil, fmt.Errorf("ent: uninitialized hook (forgotten import ent/runtime?)")
			}
			mut = muo.hooks[i](mut)
		}
		v, err := mut.Mutate(ctx, muo.mutation)
		if err != nil {
			return nil, err
		}
		nv, ok := v.(*Meta)
		if !ok {
			return nil, fmt.Errorf("unexpected node type %T returned from MetaMutation", v)
		}
		node = nv
	}
	return node, err
}

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

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

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

// defaults sets the default values of the builder before save.
func (muo *MetaUpdateOne) defaults() {
	if _, ok := muo.mutation.CreatedAt(); !ok && !muo.mutation.CreatedAtCleared() {
		v := meta.UpdateDefaultCreatedAt()
		muo.mutation.SetCreatedAt(v)
	}
	if _, ok := muo.mutation.UpdatedAt(); !ok && !muo.mutation.UpdatedAtCleared() {
		v := meta.UpdateDefaultUpdatedAt()
		muo.mutation.SetUpdatedAt(v)
	}
}

// check runs all checks and user-defined validators on the builder.
func (muo *MetaUpdateOne) check() error {
	if v, ok := muo.mutation.Value(); ok {
		if err := meta.ValueValidator(v); err != nil {
			return &ValidationError{Name: "value", err: fmt.Errorf(`ent: validator failed for field "Meta.value": %w`, err)}
		}
	}
	return nil
}

func (muo *MetaUpdateOne) sqlSave(ctx context.Context) (_node *Meta, err error) {
	_spec := &sqlgraph.UpdateSpec{
		Node: &sqlgraph.NodeSpec{
			Table:   meta.Table,
			Columns: meta.Columns,
			ID: &sqlgraph.FieldSpec{
				Type:   field.TypeInt,
				Column: meta.FieldID,
			},
		},
	}
	id, ok := muo.mutation.ID()
	if !ok {
		return nil, &ValidationError{Name: "id", err: errors.New(`ent: missing "Meta.id" for update`)}
	}
	_spec.Node.ID.Value = id
	if fields := muo.fields; len(fields) > 0 {
		_spec.Node.Columns = make([]string, 0, len(fields))
		_spec.Node.Columns = append(_spec.Node.Columns, meta.FieldID)
		for _, f := range fields {
			if !meta.ValidColumn(f) {
				return nil, &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)}
			}
			if f != meta.FieldID {
				_spec.Node.Columns = append(_spec.Node.Columns, f)
			}
		}
	}
	if ps := muo.mutation.predicates; len(ps) > 0 {
		_spec.Predicate = func(selector *sql.Selector) {
			for i := range ps {
				ps[i](selector)
			}
		}
	}
	if value, ok := muo.mutation.CreatedAt(); ok {
		_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
			Type:   field.TypeTime,
			Value:  value,
			Column: meta.FieldCreatedAt,
		})
	}
	if muo.mutation.CreatedAtCleared() {
		_spec.Fields.Clear = append(_spec.Fields.Clear, &sqlgraph.FieldSpec{
			Type:   field.TypeTime,
			Column: meta.FieldCreatedAt,
		})
	}
	if value, ok := muo.mutation.UpdatedAt(); ok {
		_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
			Type:   field.TypeTime,
			Value:  value,
			Column: meta.FieldUpdatedAt,
		})
	}
	if muo.mutation.UpdatedAtCleared() {
		_spec.Fields.Clear = append(_spec.Fields.Clear, &sqlgraph.FieldSpec{
			Type:   field.TypeTime,
			Column: meta.FieldUpdatedAt,
		})
	}
	if value, ok := muo.mutation.Key(); ok {
		_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
			Type:   field.TypeString,
			Value:  value,
			Column: meta.FieldKey,
		})
	}
	if value, ok := muo.mutation.Value(); ok {
		_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
			Type:   field.TypeString,
			Value:  value,
			Column: meta.FieldValue,
		})
	}
	if muo.mutation.OwnerCleared() {
		edge := &sqlgraph.EdgeSpec{
			Rel:     sqlgraph.M2O,
			Inverse: true,
			Table:   meta.OwnerTable,
			Columns: []string{meta.OwnerColumn},
			Bidi:    false,
			Target: &sqlgraph.EdgeTarget{
				IDSpec: &sqlgraph.FieldSpec{
					Type:   field.TypeInt,
					Column: alert.FieldID,
				},
			},
		}
		_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
	}
	if nodes := muo.mutation.OwnerIDs(); len(nodes) > 0 {
		edge := &sqlgraph.EdgeSpec{
			Rel:     sqlgraph.M2O,
			Inverse: true,
			Table:   meta.OwnerTable,
			Columns: []string{meta.OwnerColumn},
			Bidi:    false,
			Target: &sqlgraph.EdgeTarget{
				IDSpec: &sqlgraph.FieldSpec{
					Type:   field.TypeInt,
					Column: alert.FieldID,
				},
			},
		}
		for _, k := range nodes {
			edge.Target.Nodes = append(edge.Target.Nodes, k)
		}
		_spec.Edges.Add = append(_spec.Edges.Add, edge)
	}
	_node = &Meta{config: muo.config}
	_spec.Assign = _node.assignValues
	_spec.ScanValues = _node.scanValues
	if err = sqlgraph.UpdateNode(ctx, muo.driver, _spec); err != nil {
		if _, ok := err.(*sqlgraph.NotFoundError); ok {
			err = &NotFoundError{meta.Label}
		} else if sqlgraph.IsConstraintError(err) {
			err = &ConstraintError{msg: err.Error(), wrap: err}
		}
		return nil, err
	}
	return _node, nil
}
