// 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/admin"
	"github.com/chaitin/MonkeyCode/backend/db/adminloginhistory"
	"github.com/chaitin/MonkeyCode/backend/db/predicate"
	"github.com/google/uuid"
)

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

// Where appends a list predicates to the AdminUpdate builder.
func (au *AdminUpdate) Where(ps ...predicate.Admin) *AdminUpdate {
	au.mutation.Where(ps...)
	return au
}

// SetUsername sets the "username" field.
func (au *AdminUpdate) SetUsername(s string) *AdminUpdate {
	au.mutation.SetUsername(s)
	return au
}

// SetNillableUsername sets the "username" field if the given value is not nil.
func (au *AdminUpdate) SetNillableUsername(s *string) *AdminUpdate {
	if s != nil {
		au.SetUsername(*s)
	}
	return au
}

// SetPassword sets the "password" field.
func (au *AdminUpdate) SetPassword(s string) *AdminUpdate {
	au.mutation.SetPassword(s)
	return au
}

// SetNillablePassword sets the "password" field if the given value is not nil.
func (au *AdminUpdate) SetNillablePassword(s *string) *AdminUpdate {
	if s != nil {
		au.SetPassword(*s)
	}
	return au
}

// SetStatus sets the "status" field.
func (au *AdminUpdate) SetStatus(cs consts.AdminStatus) *AdminUpdate {
	au.mutation.SetStatus(cs)
	return au
}

// SetNillableStatus sets the "status" field if the given value is not nil.
func (au *AdminUpdate) SetNillableStatus(cs *consts.AdminStatus) *AdminUpdate {
	if cs != nil {
		au.SetStatus(*cs)
	}
	return au
}

// SetLastActiveAt sets the "last_active_at" field.
func (au *AdminUpdate) SetLastActiveAt(t time.Time) *AdminUpdate {
	au.mutation.SetLastActiveAt(t)
	return au
}

// SetNillableLastActiveAt sets the "last_active_at" field if the given value is not nil.
func (au *AdminUpdate) SetNillableLastActiveAt(t *time.Time) *AdminUpdate {
	if t != nil {
		au.SetLastActiveAt(*t)
	}
	return au
}

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

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

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

// AddLoginHistoryIDs adds the "login_histories" edge to the AdminLoginHistory entity by IDs.
func (au *AdminUpdate) AddLoginHistoryIDs(ids ...uuid.UUID) *AdminUpdate {
	au.mutation.AddLoginHistoryIDs(ids...)
	return au
}

// AddLoginHistories adds the "login_histories" edges to the AdminLoginHistory entity.
func (au *AdminUpdate) AddLoginHistories(a ...*AdminLoginHistory) *AdminUpdate {
	ids := make([]uuid.UUID, len(a))
	for i := range a {
		ids[i] = a[i].ID
	}
	return au.AddLoginHistoryIDs(ids...)
}

// Mutation returns the AdminMutation object of the builder.
func (au *AdminUpdate) Mutation() *AdminMutation {
	return au.mutation
}

// ClearLoginHistories clears all "login_histories" edges to the AdminLoginHistory entity.
func (au *AdminUpdate) ClearLoginHistories() *AdminUpdate {
	au.mutation.ClearLoginHistories()
	return au
}

// RemoveLoginHistoryIDs removes the "login_histories" edge to AdminLoginHistory entities by IDs.
func (au *AdminUpdate) RemoveLoginHistoryIDs(ids ...uuid.UUID) *AdminUpdate {
	au.mutation.RemoveLoginHistoryIDs(ids...)
	return au
}

// RemoveLoginHistories removes "login_histories" edges to AdminLoginHistory entities.
func (au *AdminUpdate) RemoveLoginHistories(a ...*AdminLoginHistory) *AdminUpdate {
	ids := make([]uuid.UUID, len(a))
	for i := range a {
		ids[i] = a[i].ID
	}
	return au.RemoveLoginHistoryIDs(ids...)
}

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

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

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

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

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

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

func (au *AdminUpdate) sqlSave(ctx context.Context) (n int, err error) {
	_spec := sqlgraph.NewUpdateSpec(admin.Table, admin.Columns, sqlgraph.NewFieldSpec(admin.FieldID, field.TypeUUID))
	if ps := au.mutation.predicates; len(ps) > 0 {
		_spec.Predicate = func(selector *sql.Selector) {
			for i := range ps {
				ps[i](selector)
			}
		}
	}
	if value, ok := au.mutation.Username(); ok {
		_spec.SetField(admin.FieldUsername, field.TypeString, value)
	}
	if value, ok := au.mutation.Password(); ok {
		_spec.SetField(admin.FieldPassword, field.TypeString, value)
	}
	if value, ok := au.mutation.Status(); ok {
		_spec.SetField(admin.FieldStatus, field.TypeString, value)
	}
	if value, ok := au.mutation.LastActiveAt(); ok {
		_spec.SetField(admin.FieldLastActiveAt, field.TypeTime, value)
	}
	if value, ok := au.mutation.CreatedAt(); ok {
		_spec.SetField(admin.FieldCreatedAt, field.TypeTime, value)
	}
	if value, ok := au.mutation.UpdatedAt(); ok {
		_spec.SetField(admin.FieldUpdatedAt, field.TypeTime, value)
	}
	if au.mutation.LoginHistoriesCleared() {
		edge := &sqlgraph.EdgeSpec{
			Rel:     sqlgraph.O2M,
			Inverse: false,
			Table:   admin.LoginHistoriesTable,
			Columns: []string{admin.LoginHistoriesColumn},
			Bidi:    false,
			Target: &sqlgraph.EdgeTarget{
				IDSpec: sqlgraph.NewFieldSpec(adminloginhistory.FieldID, field.TypeUUID),
			},
		}
		_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
	}
	if nodes := au.mutation.RemovedLoginHistoriesIDs(); len(nodes) > 0 && !au.mutation.LoginHistoriesCleared() {
		edge := &sqlgraph.EdgeSpec{
			Rel:     sqlgraph.O2M,
			Inverse: false,
			Table:   admin.LoginHistoriesTable,
			Columns: []string{admin.LoginHistoriesColumn},
			Bidi:    false,
			Target: &sqlgraph.EdgeTarget{
				IDSpec: sqlgraph.NewFieldSpec(adminloginhistory.FieldID, field.TypeUUID),
			},
		}
		for _, k := range nodes {
			edge.Target.Nodes = append(edge.Target.Nodes, k)
		}
		_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
	}
	if nodes := au.mutation.LoginHistoriesIDs(); len(nodes) > 0 {
		edge := &sqlgraph.EdgeSpec{
			Rel:     sqlgraph.O2M,
			Inverse: false,
			Table:   admin.LoginHistoriesTable,
			Columns: []string{admin.LoginHistoriesColumn},
			Bidi:    false,
			Target: &sqlgraph.EdgeTarget{
				IDSpec: sqlgraph.NewFieldSpec(adminloginhistory.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(au.modifiers...)
	if n, err = sqlgraph.UpdateNodes(ctx, au.driver, _spec); err != nil {
		if _, ok := err.(*sqlgraph.NotFoundError); ok {
			err = &NotFoundError{admin.Label}
		} else if sqlgraph.IsConstraintError(err) {
			err = &ConstraintError{msg: err.Error(), wrap: err}
		}
		return 0, err
	}
	au.mutation.done = true
	return n, nil
}

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

// SetUsername sets the "username" field.
func (auo *AdminUpdateOne) SetUsername(s string) *AdminUpdateOne {
	auo.mutation.SetUsername(s)
	return auo
}

// SetNillableUsername sets the "username" field if the given value is not nil.
func (auo *AdminUpdateOne) SetNillableUsername(s *string) *AdminUpdateOne {
	if s != nil {
		auo.SetUsername(*s)
	}
	return auo
}

// SetPassword sets the "password" field.
func (auo *AdminUpdateOne) SetPassword(s string) *AdminUpdateOne {
	auo.mutation.SetPassword(s)
	return auo
}

// SetNillablePassword sets the "password" field if the given value is not nil.
func (auo *AdminUpdateOne) SetNillablePassword(s *string) *AdminUpdateOne {
	if s != nil {
		auo.SetPassword(*s)
	}
	return auo
}

// SetStatus sets the "status" field.
func (auo *AdminUpdateOne) SetStatus(cs consts.AdminStatus) *AdminUpdateOne {
	auo.mutation.SetStatus(cs)
	return auo
}

// SetNillableStatus sets the "status" field if the given value is not nil.
func (auo *AdminUpdateOne) SetNillableStatus(cs *consts.AdminStatus) *AdminUpdateOne {
	if cs != nil {
		auo.SetStatus(*cs)
	}
	return auo
}

// SetLastActiveAt sets the "last_active_at" field.
func (auo *AdminUpdateOne) SetLastActiveAt(t time.Time) *AdminUpdateOne {
	auo.mutation.SetLastActiveAt(t)
	return auo
}

// SetNillableLastActiveAt sets the "last_active_at" field if the given value is not nil.
func (auo *AdminUpdateOne) SetNillableLastActiveAt(t *time.Time) *AdminUpdateOne {
	if t != nil {
		auo.SetLastActiveAt(*t)
	}
	return auo
}

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

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

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

// AddLoginHistoryIDs adds the "login_histories" edge to the AdminLoginHistory entity by IDs.
func (auo *AdminUpdateOne) AddLoginHistoryIDs(ids ...uuid.UUID) *AdminUpdateOne {
	auo.mutation.AddLoginHistoryIDs(ids...)
	return auo
}

// AddLoginHistories adds the "login_histories" edges to the AdminLoginHistory entity.
func (auo *AdminUpdateOne) AddLoginHistories(a ...*AdminLoginHistory) *AdminUpdateOne {
	ids := make([]uuid.UUID, len(a))
	for i := range a {
		ids[i] = a[i].ID
	}
	return auo.AddLoginHistoryIDs(ids...)
}

// Mutation returns the AdminMutation object of the builder.
func (auo *AdminUpdateOne) Mutation() *AdminMutation {
	return auo.mutation
}

// ClearLoginHistories clears all "login_histories" edges to the AdminLoginHistory entity.
func (auo *AdminUpdateOne) ClearLoginHistories() *AdminUpdateOne {
	auo.mutation.ClearLoginHistories()
	return auo
}

// RemoveLoginHistoryIDs removes the "login_histories" edge to AdminLoginHistory entities by IDs.
func (auo *AdminUpdateOne) RemoveLoginHistoryIDs(ids ...uuid.UUID) *AdminUpdateOne {
	auo.mutation.RemoveLoginHistoryIDs(ids...)
	return auo
}

// RemoveLoginHistories removes "login_histories" edges to AdminLoginHistory entities.
func (auo *AdminUpdateOne) RemoveLoginHistories(a ...*AdminLoginHistory) *AdminUpdateOne {
	ids := make([]uuid.UUID, len(a))
	for i := range a {
		ids[i] = a[i].ID
	}
	return auo.RemoveLoginHistoryIDs(ids...)
}

// Where appends a list predicates to the AdminUpdate builder.
func (auo *AdminUpdateOne) Where(ps ...predicate.Admin) *AdminUpdateOne {
	auo.mutation.Where(ps...)
	return auo
}

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

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

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

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

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

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

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

func (auo *AdminUpdateOne) sqlSave(ctx context.Context) (_node *Admin, err error) {
	_spec := sqlgraph.NewUpdateSpec(admin.Table, admin.Columns, sqlgraph.NewFieldSpec(admin.FieldID, field.TypeUUID))
	id, ok := auo.mutation.ID()
	if !ok {
		return nil, &ValidationError{Name: "id", err: errors.New(`db: missing "Admin.id" for update`)}
	}
	_spec.Node.ID.Value = id
	if fields := auo.fields; len(fields) > 0 {
		_spec.Node.Columns = make([]string, 0, len(fields))
		_spec.Node.Columns = append(_spec.Node.Columns, admin.FieldID)
		for _, f := range fields {
			if !admin.ValidColumn(f) {
				return nil, &ValidationError{Name: f, err: fmt.Errorf("db: invalid field %q for query", f)}
			}
			if f != admin.FieldID {
				_spec.Node.Columns = append(_spec.Node.Columns, f)
			}
		}
	}
	if ps := auo.mutation.predicates; len(ps) > 0 {
		_spec.Predicate = func(selector *sql.Selector) {
			for i := range ps {
				ps[i](selector)
			}
		}
	}
	if value, ok := auo.mutation.Username(); ok {
		_spec.SetField(admin.FieldUsername, field.TypeString, value)
	}
	if value, ok := auo.mutation.Password(); ok {
		_spec.SetField(admin.FieldPassword, field.TypeString, value)
	}
	if value, ok := auo.mutation.Status(); ok {
		_spec.SetField(admin.FieldStatus, field.TypeString, value)
	}
	if value, ok := auo.mutation.LastActiveAt(); ok {
		_spec.SetField(admin.FieldLastActiveAt, field.TypeTime, value)
	}
	if value, ok := auo.mutation.CreatedAt(); ok {
		_spec.SetField(admin.FieldCreatedAt, field.TypeTime, value)
	}
	if value, ok := auo.mutation.UpdatedAt(); ok {
		_spec.SetField(admin.FieldUpdatedAt, field.TypeTime, value)
	}
	if auo.mutation.LoginHistoriesCleared() {
		edge := &sqlgraph.EdgeSpec{
			Rel:     sqlgraph.O2M,
			Inverse: false,
			Table:   admin.LoginHistoriesTable,
			Columns: []string{admin.LoginHistoriesColumn},
			Bidi:    false,
			Target: &sqlgraph.EdgeTarget{
				IDSpec: sqlgraph.NewFieldSpec(adminloginhistory.FieldID, field.TypeUUID),
			},
		}
		_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
	}
	if nodes := auo.mutation.RemovedLoginHistoriesIDs(); len(nodes) > 0 && !auo.mutation.LoginHistoriesCleared() {
		edge := &sqlgraph.EdgeSpec{
			Rel:     sqlgraph.O2M,
			Inverse: false,
			Table:   admin.LoginHistoriesTable,
			Columns: []string{admin.LoginHistoriesColumn},
			Bidi:    false,
			Target: &sqlgraph.EdgeTarget{
				IDSpec: sqlgraph.NewFieldSpec(adminloginhistory.FieldID, field.TypeUUID),
			},
		}
		for _, k := range nodes {
			edge.Target.Nodes = append(edge.Target.Nodes, k)
		}
		_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
	}
	if nodes := auo.mutation.LoginHistoriesIDs(); len(nodes) > 0 {
		edge := &sqlgraph.EdgeSpec{
			Rel:     sqlgraph.O2M,
			Inverse: false,
			Table:   admin.LoginHistoriesTable,
			Columns: []string{admin.LoginHistoriesColumn},
			Bidi:    false,
			Target: &sqlgraph.EdgeTarget{
				IDSpec: sqlgraph.NewFieldSpec(adminloginhistory.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(auo.modifiers...)
	_node = &Admin{config: auo.config}
	_spec.Assign = _node.assignValues
	_spec.ScanValues = _node.scanValues
	if err = sqlgraph.UpdateNode(ctx, auo.driver, _spec); err != nil {
		if _, ok := err.(*sqlgraph.NotFoundError); ok {
			err = &NotFoundError{admin.Label}
		} else if sqlgraph.IsConstraintError(err) {
			err = &ConstraintError{msg: err.Error(), wrap: err}
		}
		return nil, err
	}
	auo.mutation.done = true
	return _node, nil
}
