// Code generated by ent, DO NOT EDIT.

package db

import (
	"context"
	"errors"
	"fmt"
	"time"

	"entgo.io/ent/dialect/sql"
	"entgo.io/ent/dialect/sql/sqlgraph"
	"entgo.io/ent/schema/field"
	"github.com/chaitin/MonkeyCode/backend/consts"
	"github.com/chaitin/MonkeyCode/backend/db/predicate"
	"github.com/chaitin/MonkeyCode/backend/db/task"
	"github.com/chaitin/MonkeyCode/backend/db/taskrecord"
	"github.com/google/uuid"
)

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

// Where appends a list predicates to the TaskRecordUpdate builder.
func (tru *TaskRecordUpdate) Where(ps ...predicate.TaskRecord) *TaskRecordUpdate {
	tru.mutation.Where(ps...)
	return tru
}

// SetTaskID sets the "task_id" field.
func (tru *TaskRecordUpdate) SetTaskID(u uuid.UUID) *TaskRecordUpdate {
	tru.mutation.SetTaskID(u)
	return tru
}

// SetNillableTaskID sets the "task_id" field if the given value is not nil.
func (tru *TaskRecordUpdate) SetNillableTaskID(u *uuid.UUID) *TaskRecordUpdate {
	if u != nil {
		tru.SetTaskID(*u)
	}
	return tru
}

// ClearTaskID clears the value of the "task_id" field.
func (tru *TaskRecordUpdate) ClearTaskID() *TaskRecordUpdate {
	tru.mutation.ClearTaskID()
	return tru
}

// SetPrompt sets the "prompt" field.
func (tru *TaskRecordUpdate) SetPrompt(s string) *TaskRecordUpdate {
	tru.mutation.SetPrompt(s)
	return tru
}

// SetNillablePrompt sets the "prompt" field if the given value is not nil.
func (tru *TaskRecordUpdate) SetNillablePrompt(s *string) *TaskRecordUpdate {
	if s != nil {
		tru.SetPrompt(*s)
	}
	return tru
}

// ClearPrompt clears the value of the "prompt" field.
func (tru *TaskRecordUpdate) ClearPrompt() *TaskRecordUpdate {
	tru.mutation.ClearPrompt()
	return tru
}

// SetRole sets the "role" field.
func (tru *TaskRecordUpdate) SetRole(cr consts.ChatRole) *TaskRecordUpdate {
	tru.mutation.SetRole(cr)
	return tru
}

// SetNillableRole sets the "role" field if the given value is not nil.
func (tru *TaskRecordUpdate) SetNillableRole(cr *consts.ChatRole) *TaskRecordUpdate {
	if cr != nil {
		tru.SetRole(*cr)
	}
	return tru
}

// SetCompletion sets the "completion" field.
func (tru *TaskRecordUpdate) SetCompletion(s string) *TaskRecordUpdate {
	tru.mutation.SetCompletion(s)
	return tru
}

// SetNillableCompletion sets the "completion" field if the given value is not nil.
func (tru *TaskRecordUpdate) SetNillableCompletion(s *string) *TaskRecordUpdate {
	if s != nil {
		tru.SetCompletion(*s)
	}
	return tru
}

// SetOutputTokens sets the "output_tokens" field.
func (tru *TaskRecordUpdate) SetOutputTokens(i int64) *TaskRecordUpdate {
	tru.mutation.ResetOutputTokens()
	tru.mutation.SetOutputTokens(i)
	return tru
}

// SetNillableOutputTokens sets the "output_tokens" field if the given value is not nil.
func (tru *TaskRecordUpdate) SetNillableOutputTokens(i *int64) *TaskRecordUpdate {
	if i != nil {
		tru.SetOutputTokens(*i)
	}
	return tru
}

// AddOutputTokens adds i to the "output_tokens" field.
func (tru *TaskRecordUpdate) AddOutputTokens(i int64) *TaskRecordUpdate {
	tru.mutation.AddOutputTokens(i)
	return tru
}

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

// SetNillableCreatedAt sets the "created_at" field if the given value is not nil.
func (tru *TaskRecordUpdate) SetNillableCreatedAt(t *time.Time) *TaskRecordUpdate {
	if t != nil {
		tru.SetCreatedAt(*t)
	}
	return tru
}

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

// SetTask sets the "task" edge to the Task entity.
func (tru *TaskRecordUpdate) SetTask(t *Task) *TaskRecordUpdate {
	return tru.SetTaskID(t.ID)
}

// Mutation returns the TaskRecordMutation object of the builder.
func (tru *TaskRecordUpdate) Mutation() *TaskRecordMutation {
	return tru.mutation
}

// ClearTask clears the "task" edge to the Task entity.
func (tru *TaskRecordUpdate) ClearTask() *TaskRecordUpdate {
	tru.mutation.ClearTask()
	return tru
}

// Save executes the query and returns the number of nodes affected by the update operation.
func (tru *TaskRecordUpdate) Save(ctx context.Context) (int, error) {
	tru.defaults()
	return withHooks(ctx, tru.sqlSave, tru.mutation, tru.hooks)
}

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

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

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

// defaults sets the default values of the builder before save.
func (tru *TaskRecordUpdate) defaults() {
	if _, ok := tru.mutation.UpdatedAt(); !ok {
		v := taskrecord.UpdateDefaultUpdatedAt()
		tru.mutation.SetUpdatedAt(v)
	}
}

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

func (tru *TaskRecordUpdate) sqlSave(ctx context.Context) (n int, err error) {
	_spec := sqlgraph.NewUpdateSpec(taskrecord.Table, taskrecord.Columns, sqlgraph.NewFieldSpec(taskrecord.FieldID, field.TypeUUID))
	if ps := tru.mutation.predicates; len(ps) > 0 {
		_spec.Predicate = func(selector *sql.Selector) {
			for i := range ps {
				ps[i](selector)
			}
		}
	}
	if value, ok := tru.mutation.Prompt(); ok {
		_spec.SetField(taskrecord.FieldPrompt, field.TypeString, value)
	}
	if tru.mutation.PromptCleared() {
		_spec.ClearField(taskrecord.FieldPrompt, field.TypeString)
	}
	if value, ok := tru.mutation.Role(); ok {
		_spec.SetField(taskrecord.FieldRole, field.TypeString, value)
	}
	if value, ok := tru.mutation.Completion(); ok {
		_spec.SetField(taskrecord.FieldCompletion, field.TypeString, value)
	}
	if value, ok := tru.mutation.OutputTokens(); ok {
		_spec.SetField(taskrecord.FieldOutputTokens, field.TypeInt64, value)
	}
	if value, ok := tru.mutation.AddedOutputTokens(); ok {
		_spec.AddField(taskrecord.FieldOutputTokens, field.TypeInt64, value)
	}
	if value, ok := tru.mutation.CreatedAt(); ok {
		_spec.SetField(taskrecord.FieldCreatedAt, field.TypeTime, value)
	}
	if value, ok := tru.mutation.UpdatedAt(); ok {
		_spec.SetField(taskrecord.FieldUpdatedAt, field.TypeTime, value)
	}
	if tru.mutation.TaskCleared() {
		edge := &sqlgraph.EdgeSpec{
			Rel:     sqlgraph.M2O,
			Inverse: true,
			Table:   taskrecord.TaskTable,
			Columns: []string{taskrecord.TaskColumn},
			Bidi:    false,
			Target: &sqlgraph.EdgeTarget{
				IDSpec: sqlgraph.NewFieldSpec(task.FieldID, field.TypeUUID),
			},
		}
		_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
	}
	if nodes := tru.mutation.TaskIDs(); len(nodes) > 0 {
		edge := &sqlgraph.EdgeSpec{
			Rel:     sqlgraph.M2O,
			Inverse: true,
			Table:   taskrecord.TaskTable,
			Columns: []string{taskrecord.TaskColumn},
			Bidi:    false,
			Target: &sqlgraph.EdgeTarget{
				IDSpec: sqlgraph.NewFieldSpec(task.FieldID, field.TypeUUID),
			},
		}
		for _, k := range nodes {
			edge.Target.Nodes = append(edge.Target.Nodes, k)
		}
		_spec.Edges.Add = append(_spec.Edges.Add, edge)
	}
	_spec.AddModifiers(tru.modifiers...)
	if n, err = sqlgraph.UpdateNodes(ctx, tru.driver, _spec); err != nil {
		if _, ok := err.(*sqlgraph.NotFoundError); ok {
			err = &NotFoundError{taskrecord.Label}
		} else if sqlgraph.IsConstraintError(err) {
			err = &ConstraintError{msg: err.Error(), wrap: err}
		}
		return 0, err
	}
	tru.mutation.done = true
	return n, nil
}

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

// SetTaskID sets the "task_id" field.
func (truo *TaskRecordUpdateOne) SetTaskID(u uuid.UUID) *TaskRecordUpdateOne {
	truo.mutation.SetTaskID(u)
	return truo
}

// SetNillableTaskID sets the "task_id" field if the given value is not nil.
func (truo *TaskRecordUpdateOne) SetNillableTaskID(u *uuid.UUID) *TaskRecordUpdateOne {
	if u != nil {
		truo.SetTaskID(*u)
	}
	return truo
}

// ClearTaskID clears the value of the "task_id" field.
func (truo *TaskRecordUpdateOne) ClearTaskID() *TaskRecordUpdateOne {
	truo.mutation.ClearTaskID()
	return truo
}

// SetPrompt sets the "prompt" field.
func (truo *TaskRecordUpdateOne) SetPrompt(s string) *TaskRecordUpdateOne {
	truo.mutation.SetPrompt(s)
	return truo
}

// SetNillablePrompt sets the "prompt" field if the given value is not nil.
func (truo *TaskRecordUpdateOne) SetNillablePrompt(s *string) *TaskRecordUpdateOne {
	if s != nil {
		truo.SetPrompt(*s)
	}
	return truo
}

// ClearPrompt clears the value of the "prompt" field.
func (truo *TaskRecordUpdateOne) ClearPrompt() *TaskRecordUpdateOne {
	truo.mutation.ClearPrompt()
	return truo
}

// SetRole sets the "role" field.
func (truo *TaskRecordUpdateOne) SetRole(cr consts.ChatRole) *TaskRecordUpdateOne {
	truo.mutation.SetRole(cr)
	return truo
}

// SetNillableRole sets the "role" field if the given value is not nil.
func (truo *TaskRecordUpdateOne) SetNillableRole(cr *consts.ChatRole) *TaskRecordUpdateOne {
	if cr != nil {
		truo.SetRole(*cr)
	}
	return truo
}

// SetCompletion sets the "completion" field.
func (truo *TaskRecordUpdateOne) SetCompletion(s string) *TaskRecordUpdateOne {
	truo.mutation.SetCompletion(s)
	return truo
}

// SetNillableCompletion sets the "completion" field if the given value is not nil.
func (truo *TaskRecordUpdateOne) SetNillableCompletion(s *string) *TaskRecordUpdateOne {
	if s != nil {
		truo.SetCompletion(*s)
	}
	return truo
}

// SetOutputTokens sets the "output_tokens" field.
func (truo *TaskRecordUpdateOne) SetOutputTokens(i int64) *TaskRecordUpdateOne {
	truo.mutation.ResetOutputTokens()
	truo.mutation.SetOutputTokens(i)
	return truo
}

// SetNillableOutputTokens sets the "output_tokens" field if the given value is not nil.
func (truo *TaskRecordUpdateOne) SetNillableOutputTokens(i *int64) *TaskRecordUpdateOne {
	if i != nil {
		truo.SetOutputTokens(*i)
	}
	return truo
}

// AddOutputTokens adds i to the "output_tokens" field.
func (truo *TaskRecordUpdateOne) AddOutputTokens(i int64) *TaskRecordUpdateOne {
	truo.mutation.AddOutputTokens(i)
	return truo
}

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

// SetNillableCreatedAt sets the "created_at" field if the given value is not nil.
func (truo *TaskRecordUpdateOne) SetNillableCreatedAt(t *time.Time) *TaskRecordUpdateOne {
	if t != nil {
		truo.SetCreatedAt(*t)
	}
	return truo
}

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

// SetTask sets the "task" edge to the Task entity.
func (truo *TaskRecordUpdateOne) SetTask(t *Task) *TaskRecordUpdateOne {
	return truo.SetTaskID(t.ID)
}

// Mutation returns the TaskRecordMutation object of the builder.
func (truo *TaskRecordUpdateOne) Mutation() *TaskRecordMutation {
	return truo.mutation
}

// ClearTask clears the "task" edge to the Task entity.
func (truo *TaskRecordUpdateOne) ClearTask() *TaskRecordUpdateOne {
	truo.mutation.ClearTask()
	return truo
}

// Where appends a list predicates to the TaskRecordUpdate builder.
func (truo *TaskRecordUpdateOne) Where(ps ...predicate.TaskRecord) *TaskRecordUpdateOne {
	truo.mutation.Where(ps...)
	return truo
}

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

// Save executes the query and returns the updated TaskRecord entity.
func (truo *TaskRecordUpdateOne) Save(ctx context.Context) (*TaskRecord, error) {
	truo.defaults()
	return withHooks(ctx, truo.sqlSave, truo.mutation, truo.hooks)
}

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

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

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

// defaults sets the default values of the builder before save.
func (truo *TaskRecordUpdateOne) defaults() {
	if _, ok := truo.mutation.UpdatedAt(); !ok {
		v := taskrecord.UpdateDefaultUpdatedAt()
		truo.mutation.SetUpdatedAt(v)
	}
}

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

func (truo *TaskRecordUpdateOne) sqlSave(ctx context.Context) (_node *TaskRecord, err error) {
	_spec := sqlgraph.NewUpdateSpec(taskrecord.Table, taskrecord.Columns, sqlgraph.NewFieldSpec(taskrecord.FieldID, field.TypeUUID))
	id, ok := truo.mutation.ID()
	if !ok {
		return nil, &ValidationError{Name: "id", err: errors.New(`db: missing "TaskRecord.id" for update`)}
	}
	_spec.Node.ID.Value = id
	if fields := truo.fields; len(fields) > 0 {
		_spec.Node.Columns = make([]string, 0, len(fields))
		_spec.Node.Columns = append(_spec.Node.Columns, taskrecord.FieldID)
		for _, f := range fields {
			if !taskrecord.ValidColumn(f) {
				return nil, &ValidationError{Name: f, err: fmt.Errorf("db: invalid field %q for query", f)}
			}
			if f != taskrecord.FieldID {
				_spec.Node.Columns = append(_spec.Node.Columns, f)
			}
		}
	}
	if ps := truo.mutation.predicates; len(ps) > 0 {
		_spec.Predicate = func(selector *sql.Selector) {
			for i := range ps {
				ps[i](selector)
			}
		}
	}
	if value, ok := truo.mutation.Prompt(); ok {
		_spec.SetField(taskrecord.FieldPrompt, field.TypeString, value)
	}
	if truo.mutation.PromptCleared() {
		_spec.ClearField(taskrecord.FieldPrompt, field.TypeString)
	}
	if value, ok := truo.mutation.Role(); ok {
		_spec.SetField(taskrecord.FieldRole, field.TypeString, value)
	}
	if value, ok := truo.mutation.Completion(); ok {
		_spec.SetField(taskrecord.FieldCompletion, field.TypeString, value)
	}
	if value, ok := truo.mutation.OutputTokens(); ok {
		_spec.SetField(taskrecord.FieldOutputTokens, field.TypeInt64, value)
	}
	if value, ok := truo.mutation.AddedOutputTokens(); ok {
		_spec.AddField(taskrecord.FieldOutputTokens, field.TypeInt64, value)
	}
	if value, ok := truo.mutation.CreatedAt(); ok {
		_spec.SetField(taskrecord.FieldCreatedAt, field.TypeTime, value)
	}
	if value, ok := truo.mutation.UpdatedAt(); ok {
		_spec.SetField(taskrecord.FieldUpdatedAt, field.TypeTime, value)
	}
	if truo.mutation.TaskCleared() {
		edge := &sqlgraph.EdgeSpec{
			Rel:     sqlgraph.M2O,
			Inverse: true,
			Table:   taskrecord.TaskTable,
			Columns: []string{taskrecord.TaskColumn},
			Bidi:    false,
			Target: &sqlgraph.EdgeTarget{
				IDSpec: sqlgraph.NewFieldSpec(task.FieldID, field.TypeUUID),
			},
		}
		_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
	}
	if nodes := truo.mutation.TaskIDs(); len(nodes) > 0 {
		edge := &sqlgraph.EdgeSpec{
			Rel:     sqlgraph.M2O,
			Inverse: true,
			Table:   taskrecord.TaskTable,
			Columns: []string{taskrecord.TaskColumn},
			Bidi:    false,
			Target: &sqlgraph.EdgeTarget{
				IDSpec: sqlgraph.NewFieldSpec(task.FieldID, field.TypeUUID),
			},
		}
		for _, k := range nodes {
			edge.Target.Nodes = append(edge.Target.Nodes, k)
		}
		_spec.Edges.Add = append(_spec.Edges.Add, edge)
	}
	_spec.AddModifiers(truo.modifiers...)
	_node = &TaskRecord{config: truo.config}
	_spec.Assign = _node.assignValues
	_spec.ScanValues = _node.scanValues
	if err = sqlgraph.UpdateNode(ctx, truo.driver, _spec); err != nil {
		if _, ok := err.(*sqlgraph.NotFoundError); ok {
			err = &NotFoundError{taskrecord.Label}
		} else if sqlgraph.IsConstraintError(err) {
			err = &ConstraintError{msg: err.Error(), wrap: err}
		}
		return nil, err
	}
	truo.mutation.done = true
	return _node, nil
}
