// Code generated by ent, DO NOT EDIT.

package ent

import (
	"context"
	"database/sql/driver"
	"fmt"
	"math"

	"entgo.io/ent"
	"entgo.io/ent/dialect"
	"entgo.io/ent/dialect/sql"
	"entgo.io/ent/dialect/sql/sqlgraph"
	"entgo.io/ent/schema/field"
	"github.com/google/uuid"
	"github.com/lightsparkdev/spark/so/ent/predicate"
	"github.com/lightsparkdev/spark/so/ent/signingkeyshare"
	"github.com/lightsparkdev/spark/so/ent/tokencreate"
	"github.com/lightsparkdev/spark/so/ent/tokenoutput"
	"github.com/lightsparkdev/spark/so/ent/tokenpartialrevocationsecretshare"
	"github.com/lightsparkdev/spark/so/ent/tokentransaction"
)

// TokenOutputQuery is the builder for querying TokenOutput entities.
type TokenOutputQuery struct {
	config
	ctx                                     *QueryContext
	order                                   []tokenoutput.OrderOption
	inters                                  []Interceptor
	predicates                              []predicate.TokenOutput
	withRevocationKeyshare                  *SigningKeyshareQuery
	withOutputCreatedTokenTransaction       *TokenTransactionQuery
	withOutputSpentTokenTransaction         *TokenTransactionQuery
	withOutputSpentStartedTokenTransactions *TokenTransactionQuery
	withTokenPartialRevocationSecretShares  *TokenPartialRevocationSecretShareQuery
	withTokenCreate                         *TokenCreateQuery
	withFKs                                 bool
	modifiers                               []func(*sql.Selector)
	// intermediate query (i.e. traversal path).
	sql  *sql.Selector
	path func(context.Context) (*sql.Selector, error)
}

// Where adds a new predicate for the TokenOutputQuery builder.
func (toq *TokenOutputQuery) Where(ps ...predicate.TokenOutput) *TokenOutputQuery {
	toq.predicates = append(toq.predicates, ps...)
	return toq
}

// Limit the number of records to be returned by this query.
func (toq *TokenOutputQuery) Limit(limit int) *TokenOutputQuery {
	toq.ctx.Limit = &limit
	return toq
}

// Offset to start from.
func (toq *TokenOutputQuery) Offset(offset int) *TokenOutputQuery {
	toq.ctx.Offset = &offset
	return toq
}

// Unique configures the query builder to filter duplicate records on query.
// By default, unique is set to true, and can be disabled using this method.
func (toq *TokenOutputQuery) Unique(unique bool) *TokenOutputQuery {
	toq.ctx.Unique = &unique
	return toq
}

// Order specifies how the records should be ordered.
func (toq *TokenOutputQuery) Order(o ...tokenoutput.OrderOption) *TokenOutputQuery {
	toq.order = append(toq.order, o...)
	return toq
}

// QueryRevocationKeyshare chains the current query on the "revocation_keyshare" edge.
func (toq *TokenOutputQuery) QueryRevocationKeyshare() *SigningKeyshareQuery {
	query := (&SigningKeyshareClient{config: toq.config}).Query()
	query.path = func(ctx context.Context) (fromU *sql.Selector, err error) {
		if err := toq.prepareQuery(ctx); err != nil {
			return nil, err
		}
		selector := toq.sqlQuery(ctx)
		if err := selector.Err(); err != nil {
			return nil, err
		}
		step := sqlgraph.NewStep(
			sqlgraph.From(tokenoutput.Table, tokenoutput.FieldID, selector),
			sqlgraph.To(signingkeyshare.Table, signingkeyshare.FieldID),
			sqlgraph.Edge(sqlgraph.M2O, false, tokenoutput.RevocationKeyshareTable, tokenoutput.RevocationKeyshareColumn),
		)
		fromU = sqlgraph.SetNeighbors(toq.driver.Dialect(), step)
		return fromU, nil
	}
	return query
}

// QueryOutputCreatedTokenTransaction chains the current query on the "output_created_token_transaction" edge.
func (toq *TokenOutputQuery) QueryOutputCreatedTokenTransaction() *TokenTransactionQuery {
	query := (&TokenTransactionClient{config: toq.config}).Query()
	query.path = func(ctx context.Context) (fromU *sql.Selector, err error) {
		if err := toq.prepareQuery(ctx); err != nil {
			return nil, err
		}
		selector := toq.sqlQuery(ctx)
		if err := selector.Err(); err != nil {
			return nil, err
		}
		step := sqlgraph.NewStep(
			sqlgraph.From(tokenoutput.Table, tokenoutput.FieldID, selector),
			sqlgraph.To(tokentransaction.Table, tokentransaction.FieldID),
			sqlgraph.Edge(sqlgraph.M2O, false, tokenoutput.OutputCreatedTokenTransactionTable, tokenoutput.OutputCreatedTokenTransactionColumn),
		)
		fromU = sqlgraph.SetNeighbors(toq.driver.Dialect(), step)
		return fromU, nil
	}
	return query
}

// QueryOutputSpentTokenTransaction chains the current query on the "output_spent_token_transaction" edge.
func (toq *TokenOutputQuery) QueryOutputSpentTokenTransaction() *TokenTransactionQuery {
	query := (&TokenTransactionClient{config: toq.config}).Query()
	query.path = func(ctx context.Context) (fromU *sql.Selector, err error) {
		if err := toq.prepareQuery(ctx); err != nil {
			return nil, err
		}
		selector := toq.sqlQuery(ctx)
		if err := selector.Err(); err != nil {
			return nil, err
		}
		step := sqlgraph.NewStep(
			sqlgraph.From(tokenoutput.Table, tokenoutput.FieldID, selector),
			sqlgraph.To(tokentransaction.Table, tokentransaction.FieldID),
			sqlgraph.Edge(sqlgraph.M2O, false, tokenoutput.OutputSpentTokenTransactionTable, tokenoutput.OutputSpentTokenTransactionColumn),
		)
		fromU = sqlgraph.SetNeighbors(toq.driver.Dialect(), step)
		return fromU, nil
	}
	return query
}

// QueryOutputSpentStartedTokenTransactions chains the current query on the "output_spent_started_token_transactions" edge.
func (toq *TokenOutputQuery) QueryOutputSpentStartedTokenTransactions() *TokenTransactionQuery {
	query := (&TokenTransactionClient{config: toq.config}).Query()
	query.path = func(ctx context.Context) (fromU *sql.Selector, err error) {
		if err := toq.prepareQuery(ctx); err != nil {
			return nil, err
		}
		selector := toq.sqlQuery(ctx)
		if err := selector.Err(); err != nil {
			return nil, err
		}
		step := sqlgraph.NewStep(
			sqlgraph.From(tokenoutput.Table, tokenoutput.FieldID, selector),
			sqlgraph.To(tokentransaction.Table, tokentransaction.FieldID),
			sqlgraph.Edge(sqlgraph.M2M, false, tokenoutput.OutputSpentStartedTokenTransactionsTable, tokenoutput.OutputSpentStartedTokenTransactionsPrimaryKey...),
		)
		fromU = sqlgraph.SetNeighbors(toq.driver.Dialect(), step)
		return fromU, nil
	}
	return query
}

// QueryTokenPartialRevocationSecretShares chains the current query on the "token_partial_revocation_secret_shares" edge.
func (toq *TokenOutputQuery) QueryTokenPartialRevocationSecretShares() *TokenPartialRevocationSecretShareQuery {
	query := (&TokenPartialRevocationSecretShareClient{config: toq.config}).Query()
	query.path = func(ctx context.Context) (fromU *sql.Selector, err error) {
		if err := toq.prepareQuery(ctx); err != nil {
			return nil, err
		}
		selector := toq.sqlQuery(ctx)
		if err := selector.Err(); err != nil {
			return nil, err
		}
		step := sqlgraph.NewStep(
			sqlgraph.From(tokenoutput.Table, tokenoutput.FieldID, selector),
			sqlgraph.To(tokenpartialrevocationsecretshare.Table, tokenpartialrevocationsecretshare.FieldID),
			sqlgraph.Edge(sqlgraph.O2M, false, tokenoutput.TokenPartialRevocationSecretSharesTable, tokenoutput.TokenPartialRevocationSecretSharesColumn),
		)
		fromU = sqlgraph.SetNeighbors(toq.driver.Dialect(), step)
		return fromU, nil
	}
	return query
}

// QueryTokenCreate chains the current query on the "token_create" edge.
func (toq *TokenOutputQuery) QueryTokenCreate() *TokenCreateQuery {
	query := (&TokenCreateClient{config: toq.config}).Query()
	query.path = func(ctx context.Context) (fromU *sql.Selector, err error) {
		if err := toq.prepareQuery(ctx); err != nil {
			return nil, err
		}
		selector := toq.sqlQuery(ctx)
		if err := selector.Err(); err != nil {
			return nil, err
		}
		step := sqlgraph.NewStep(
			sqlgraph.From(tokenoutput.Table, tokenoutput.FieldID, selector),
			sqlgraph.To(tokencreate.Table, tokencreate.FieldID),
			sqlgraph.Edge(sqlgraph.M2O, true, tokenoutput.TokenCreateTable, tokenoutput.TokenCreateColumn),
		)
		fromU = sqlgraph.SetNeighbors(toq.driver.Dialect(), step)
		return fromU, nil
	}
	return query
}

// First returns the first TokenOutput entity from the query.
// Returns a *NotFoundError when no TokenOutput was found.
func (toq *TokenOutputQuery) First(ctx context.Context) (*TokenOutput, error) {
	nodes, err := toq.Limit(1).All(setContextOp(ctx, toq.ctx, ent.OpQueryFirst))
	if err != nil {
		return nil, err
	}
	if len(nodes) == 0 {
		return nil, &NotFoundError{tokenoutput.Label}
	}
	return nodes[0], nil
}

// FirstX is like First, but panics if an error occurs.
func (toq *TokenOutputQuery) FirstX(ctx context.Context) *TokenOutput {
	node, err := toq.First(ctx)
	if err != nil && !IsNotFound(err) {
		panic(err)
	}
	return node
}

// FirstID returns the first TokenOutput ID from the query.
// Returns a *NotFoundError when no TokenOutput ID was found.
func (toq *TokenOutputQuery) FirstID(ctx context.Context) (id uuid.UUID, err error) {
	var ids []uuid.UUID
	if ids, err = toq.Limit(1).IDs(setContextOp(ctx, toq.ctx, ent.OpQueryFirstID)); err != nil {
		return
	}
	if len(ids) == 0 {
		err = &NotFoundError{tokenoutput.Label}
		return
	}
	return ids[0], nil
}

// FirstIDX is like FirstID, but panics if an error occurs.
func (toq *TokenOutputQuery) FirstIDX(ctx context.Context) uuid.UUID {
	id, err := toq.FirstID(ctx)
	if err != nil && !IsNotFound(err) {
		panic(err)
	}
	return id
}

// Only returns a single TokenOutput entity found by the query, ensuring it only returns one.
// Returns a *NotSingularError when more than one TokenOutput entity is found.
// Returns a *NotFoundError when no TokenOutput entities are found.
func (toq *TokenOutputQuery) Only(ctx context.Context) (*TokenOutput, error) {
	nodes, err := toq.Limit(2).All(setContextOp(ctx, toq.ctx, ent.OpQueryOnly))
	if err != nil {
		return nil, err
	}
	switch len(nodes) {
	case 1:
		return nodes[0], nil
	case 0:
		return nil, &NotFoundError{tokenoutput.Label}
	default:
		return nil, &NotSingularError{tokenoutput.Label}
	}
}

// OnlyX is like Only, but panics if an error occurs.
func (toq *TokenOutputQuery) OnlyX(ctx context.Context) *TokenOutput {
	node, err := toq.Only(ctx)
	if err != nil {
		panic(err)
	}
	return node
}

// OnlyID is like Only, but returns the only TokenOutput ID in the query.
// Returns a *NotSingularError when more than one TokenOutput ID is found.
// Returns a *NotFoundError when no entities are found.
func (toq *TokenOutputQuery) OnlyID(ctx context.Context) (id uuid.UUID, err error) {
	var ids []uuid.UUID
	if ids, err = toq.Limit(2).IDs(setContextOp(ctx, toq.ctx, ent.OpQueryOnlyID)); err != nil {
		return
	}
	switch len(ids) {
	case 1:
		id = ids[0]
	case 0:
		err = &NotFoundError{tokenoutput.Label}
	default:
		err = &NotSingularError{tokenoutput.Label}
	}
	return
}

// OnlyIDX is like OnlyID, but panics if an error occurs.
func (toq *TokenOutputQuery) OnlyIDX(ctx context.Context) uuid.UUID {
	id, err := toq.OnlyID(ctx)
	if err != nil {
		panic(err)
	}
	return id
}

// All executes the query and returns a list of TokenOutputs.
func (toq *TokenOutputQuery) All(ctx context.Context) ([]*TokenOutput, error) {
	ctx = setContextOp(ctx, toq.ctx, ent.OpQueryAll)
	if err := toq.prepareQuery(ctx); err != nil {
		return nil, err
	}
	qr := querierAll[[]*TokenOutput, *TokenOutputQuery]()
	return withInterceptors[[]*TokenOutput](ctx, toq, qr, toq.inters)
}

// AllX is like All, but panics if an error occurs.
func (toq *TokenOutputQuery) AllX(ctx context.Context) []*TokenOutput {
	nodes, err := toq.All(ctx)
	if err != nil {
		panic(err)
	}
	return nodes
}

// IDs executes the query and returns a list of TokenOutput IDs.
func (toq *TokenOutputQuery) IDs(ctx context.Context) (ids []uuid.UUID, err error) {
	if toq.ctx.Unique == nil && toq.path != nil {
		toq.Unique(true)
	}
	ctx = setContextOp(ctx, toq.ctx, ent.OpQueryIDs)
	if err = toq.Select(tokenoutput.FieldID).Scan(ctx, &ids); err != nil {
		return nil, err
	}
	return ids, nil
}

// IDsX is like IDs, but panics if an error occurs.
func (toq *TokenOutputQuery) IDsX(ctx context.Context) []uuid.UUID {
	ids, err := toq.IDs(ctx)
	if err != nil {
		panic(err)
	}
	return ids
}

// Count returns the count of the given query.
func (toq *TokenOutputQuery) Count(ctx context.Context) (int, error) {
	ctx = setContextOp(ctx, toq.ctx, ent.OpQueryCount)
	if err := toq.prepareQuery(ctx); err != nil {
		return 0, err
	}
	return withInterceptors[int](ctx, toq, querierCount[*TokenOutputQuery](), toq.inters)
}

// CountX is like Count, but panics if an error occurs.
func (toq *TokenOutputQuery) CountX(ctx context.Context) int {
	count, err := toq.Count(ctx)
	if err != nil {
		panic(err)
	}
	return count
}

// Exist returns true if the query has elements in the graph.
func (toq *TokenOutputQuery) Exist(ctx context.Context) (bool, error) {
	ctx = setContextOp(ctx, toq.ctx, ent.OpQueryExist)
	switch _, err := toq.FirstID(ctx); {
	case IsNotFound(err):
		return false, nil
	case err != nil:
		return false, fmt.Errorf("ent: check existence: %w", err)
	default:
		return true, nil
	}
}

// ExistX is like Exist, but panics if an error occurs.
func (toq *TokenOutputQuery) ExistX(ctx context.Context) bool {
	exist, err := toq.Exist(ctx)
	if err != nil {
		panic(err)
	}
	return exist
}

// Clone returns a duplicate of the TokenOutputQuery builder, including all associated steps. It can be
// used to prepare common query builders and use them differently after the clone is made.
func (toq *TokenOutputQuery) Clone() *TokenOutputQuery {
	if toq == nil {
		return nil
	}
	return &TokenOutputQuery{
		config:                                  toq.config,
		ctx:                                     toq.ctx.Clone(),
		order:                                   append([]tokenoutput.OrderOption{}, toq.order...),
		inters:                                  append([]Interceptor{}, toq.inters...),
		predicates:                              append([]predicate.TokenOutput{}, toq.predicates...),
		withRevocationKeyshare:                  toq.withRevocationKeyshare.Clone(),
		withOutputCreatedTokenTransaction:       toq.withOutputCreatedTokenTransaction.Clone(),
		withOutputSpentTokenTransaction:         toq.withOutputSpentTokenTransaction.Clone(),
		withOutputSpentStartedTokenTransactions: toq.withOutputSpentStartedTokenTransactions.Clone(),
		withTokenPartialRevocationSecretShares:  toq.withTokenPartialRevocationSecretShares.Clone(),
		withTokenCreate:                         toq.withTokenCreate.Clone(),
		// clone intermediate query.
		sql:  toq.sql.Clone(),
		path: toq.path,
	}
}

// WithRevocationKeyshare tells the query-builder to eager-load the nodes that are connected to
// the "revocation_keyshare" edge. The optional arguments are used to configure the query builder of the edge.
func (toq *TokenOutputQuery) WithRevocationKeyshare(opts ...func(*SigningKeyshareQuery)) *TokenOutputQuery {
	query := (&SigningKeyshareClient{config: toq.config}).Query()
	for _, opt := range opts {
		opt(query)
	}
	toq.withRevocationKeyshare = query
	return toq
}

// WithOutputCreatedTokenTransaction tells the query-builder to eager-load the nodes that are connected to
// the "output_created_token_transaction" edge. The optional arguments are used to configure the query builder of the edge.
func (toq *TokenOutputQuery) WithOutputCreatedTokenTransaction(opts ...func(*TokenTransactionQuery)) *TokenOutputQuery {
	query := (&TokenTransactionClient{config: toq.config}).Query()
	for _, opt := range opts {
		opt(query)
	}
	toq.withOutputCreatedTokenTransaction = query
	return toq
}

// WithOutputSpentTokenTransaction tells the query-builder to eager-load the nodes that are connected to
// the "output_spent_token_transaction" edge. The optional arguments are used to configure the query builder of the edge.
func (toq *TokenOutputQuery) WithOutputSpentTokenTransaction(opts ...func(*TokenTransactionQuery)) *TokenOutputQuery {
	query := (&TokenTransactionClient{config: toq.config}).Query()
	for _, opt := range opts {
		opt(query)
	}
	toq.withOutputSpentTokenTransaction = query
	return toq
}

// WithOutputSpentStartedTokenTransactions tells the query-builder to eager-load the nodes that are connected to
// the "output_spent_started_token_transactions" edge. The optional arguments are used to configure the query builder of the edge.
func (toq *TokenOutputQuery) WithOutputSpentStartedTokenTransactions(opts ...func(*TokenTransactionQuery)) *TokenOutputQuery {
	query := (&TokenTransactionClient{config: toq.config}).Query()
	for _, opt := range opts {
		opt(query)
	}
	toq.withOutputSpentStartedTokenTransactions = query
	return toq
}

// WithTokenPartialRevocationSecretShares tells the query-builder to eager-load the nodes that are connected to
// the "token_partial_revocation_secret_shares" edge. The optional arguments are used to configure the query builder of the edge.
func (toq *TokenOutputQuery) WithTokenPartialRevocationSecretShares(opts ...func(*TokenPartialRevocationSecretShareQuery)) *TokenOutputQuery {
	query := (&TokenPartialRevocationSecretShareClient{config: toq.config}).Query()
	for _, opt := range opts {
		opt(query)
	}
	toq.withTokenPartialRevocationSecretShares = query
	return toq
}

// WithTokenCreate tells the query-builder to eager-load the nodes that are connected to
// the "token_create" edge. The optional arguments are used to configure the query builder of the edge.
func (toq *TokenOutputQuery) WithTokenCreate(opts ...func(*TokenCreateQuery)) *TokenOutputQuery {
	query := (&TokenCreateClient{config: toq.config}).Query()
	for _, opt := range opts {
		opt(query)
	}
	toq.withTokenCreate = query
	return toq
}

// GroupBy is used to group vertices by one or more fields/columns.
// It is often used with aggregate functions, like: count, max, mean, min, sum.
//
// Example:
//
//	var v []struct {
//		CreateTime time.Time `json:"create_time,omitempty"`
//		Count int `json:"count,omitempty"`
//	}
//
//	client.TokenOutput.Query().
//		GroupBy(tokenoutput.FieldCreateTime).
//		Aggregate(ent.Count()).
//		Scan(ctx, &v)
func (toq *TokenOutputQuery) GroupBy(field string, fields ...string) *TokenOutputGroupBy {
	toq.ctx.Fields = append([]string{field}, fields...)
	grbuild := &TokenOutputGroupBy{build: toq}
	grbuild.flds = &toq.ctx.Fields
	grbuild.label = tokenoutput.Label
	grbuild.scan = grbuild.Scan
	return grbuild
}

// Select allows the selection one or more fields/columns for the given query,
// instead of selecting all fields in the entity.
//
// Example:
//
//	var v []struct {
//		CreateTime time.Time `json:"create_time,omitempty"`
//	}
//
//	client.TokenOutput.Query().
//		Select(tokenoutput.FieldCreateTime).
//		Scan(ctx, &v)
func (toq *TokenOutputQuery) Select(fields ...string) *TokenOutputSelect {
	toq.ctx.Fields = append(toq.ctx.Fields, fields...)
	sbuild := &TokenOutputSelect{TokenOutputQuery: toq}
	sbuild.label = tokenoutput.Label
	sbuild.flds, sbuild.scan = &toq.ctx.Fields, sbuild.Scan
	return sbuild
}

// Aggregate returns a TokenOutputSelect configured with the given aggregations.
func (toq *TokenOutputQuery) Aggregate(fns ...AggregateFunc) *TokenOutputSelect {
	return toq.Select().Aggregate(fns...)
}

func (toq *TokenOutputQuery) prepareQuery(ctx context.Context) error {
	for _, inter := range toq.inters {
		if inter == nil {
			return fmt.Errorf("ent: uninitialized interceptor (forgotten import ent/runtime?)")
		}
		if trv, ok := inter.(Traverser); ok {
			if err := trv.Traverse(ctx, toq); err != nil {
				return err
			}
		}
	}
	for _, f := range toq.ctx.Fields {
		if !tokenoutput.ValidColumn(f) {
			return &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)}
		}
	}
	if toq.path != nil {
		prev, err := toq.path(ctx)
		if err != nil {
			return err
		}
		toq.sql = prev
	}
	return nil
}

func (toq *TokenOutputQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*TokenOutput, error) {
	var (
		nodes       = []*TokenOutput{}
		withFKs     = toq.withFKs
		_spec       = toq.querySpec()
		loadedTypes = [6]bool{
			toq.withRevocationKeyshare != nil,
			toq.withOutputCreatedTokenTransaction != nil,
			toq.withOutputSpentTokenTransaction != nil,
			toq.withOutputSpentStartedTokenTransactions != nil,
			toq.withTokenPartialRevocationSecretShares != nil,
			toq.withTokenCreate != nil,
		}
	)
	if toq.withRevocationKeyshare != nil || toq.withOutputCreatedTokenTransaction != nil || toq.withOutputSpentTokenTransaction != nil {
		withFKs = true
	}
	if withFKs {
		_spec.Node.Columns = append(_spec.Node.Columns, tokenoutput.ForeignKeys...)
	}
	_spec.ScanValues = func(columns []string) ([]any, error) {
		return (*TokenOutput).scanValues(nil, columns)
	}
	_spec.Assign = func(columns []string, values []any) error {
		node := &TokenOutput{config: toq.config}
		nodes = append(nodes, node)
		node.Edges.loadedTypes = loadedTypes
		return node.assignValues(columns, values)
	}
	if len(toq.modifiers) > 0 {
		_spec.Modifiers = toq.modifiers
	}
	for i := range hooks {
		hooks[i](ctx, _spec)
	}
	if err := sqlgraph.QueryNodes(ctx, toq.driver, _spec); err != nil {
		return nil, err
	}
	if len(nodes) == 0 {
		return nodes, nil
	}
	if query := toq.withRevocationKeyshare; query != nil {
		if err := toq.loadRevocationKeyshare(ctx, query, nodes, nil,
			func(n *TokenOutput, e *SigningKeyshare) { n.Edges.RevocationKeyshare = e }); err != nil {
			return nil, err
		}
	}
	if query := toq.withOutputCreatedTokenTransaction; query != nil {
		if err := toq.loadOutputCreatedTokenTransaction(ctx, query, nodes, nil,
			func(n *TokenOutput, e *TokenTransaction) { n.Edges.OutputCreatedTokenTransaction = e }); err != nil {
			return nil, err
		}
	}
	if query := toq.withOutputSpentTokenTransaction; query != nil {
		if err := toq.loadOutputSpentTokenTransaction(ctx, query, nodes, nil,
			func(n *TokenOutput, e *TokenTransaction) { n.Edges.OutputSpentTokenTransaction = e }); err != nil {
			return nil, err
		}
	}
	if query := toq.withOutputSpentStartedTokenTransactions; query != nil {
		if err := toq.loadOutputSpentStartedTokenTransactions(ctx, query, nodes,
			func(n *TokenOutput) { n.Edges.OutputSpentStartedTokenTransactions = []*TokenTransaction{} },
			func(n *TokenOutput, e *TokenTransaction) {
				n.Edges.OutputSpentStartedTokenTransactions = append(n.Edges.OutputSpentStartedTokenTransactions, e)
			}); err != nil {
			return nil, err
		}
	}
	if query := toq.withTokenPartialRevocationSecretShares; query != nil {
		if err := toq.loadTokenPartialRevocationSecretShares(ctx, query, nodes,
			func(n *TokenOutput) {
				n.Edges.TokenPartialRevocationSecretShares = []*TokenPartialRevocationSecretShare{}
			},
			func(n *TokenOutput, e *TokenPartialRevocationSecretShare) {
				n.Edges.TokenPartialRevocationSecretShares = append(n.Edges.TokenPartialRevocationSecretShares, e)
			}); err != nil {
			return nil, err
		}
	}
	if query := toq.withTokenCreate; query != nil {
		if err := toq.loadTokenCreate(ctx, query, nodes, nil,
			func(n *TokenOutput, e *TokenCreate) { n.Edges.TokenCreate = e }); err != nil {
			return nil, err
		}
	}
	return nodes, nil
}

func (toq *TokenOutputQuery) loadRevocationKeyshare(ctx context.Context, query *SigningKeyshareQuery, nodes []*TokenOutput, init func(*TokenOutput), assign func(*TokenOutput, *SigningKeyshare)) error {
	ids := make([]uuid.UUID, 0, len(nodes))
	nodeids := make(map[uuid.UUID][]*TokenOutput)
	for i := range nodes {
		if nodes[i].token_output_revocation_keyshare == nil {
			continue
		}
		fk := *nodes[i].token_output_revocation_keyshare
		if _, ok := nodeids[fk]; !ok {
			ids = append(ids, fk)
		}
		nodeids[fk] = append(nodeids[fk], nodes[i])
	}
	if len(ids) == 0 {
		return nil
	}
	query.Where(signingkeyshare.IDIn(ids...))
	neighbors, err := query.All(ctx)
	if err != nil {
		return err
	}
	for _, n := range neighbors {
		nodes, ok := nodeids[n.ID]
		if !ok {
			return fmt.Errorf(`unexpected foreign-key "token_output_revocation_keyshare" returned %v`, n.ID)
		}
		for i := range nodes {
			assign(nodes[i], n)
		}
	}
	return nil
}
func (toq *TokenOutputQuery) loadOutputCreatedTokenTransaction(ctx context.Context, query *TokenTransactionQuery, nodes []*TokenOutput, init func(*TokenOutput), assign func(*TokenOutput, *TokenTransaction)) error {
	ids := make([]uuid.UUID, 0, len(nodes))
	nodeids := make(map[uuid.UUID][]*TokenOutput)
	for i := range nodes {
		if nodes[i].token_output_output_created_token_transaction == nil {
			continue
		}
		fk := *nodes[i].token_output_output_created_token_transaction
		if _, ok := nodeids[fk]; !ok {
			ids = append(ids, fk)
		}
		nodeids[fk] = append(nodeids[fk], nodes[i])
	}
	if len(ids) == 0 {
		return nil
	}
	query.Where(tokentransaction.IDIn(ids...))
	neighbors, err := query.All(ctx)
	if err != nil {
		return err
	}
	for _, n := range neighbors {
		nodes, ok := nodeids[n.ID]
		if !ok {
			return fmt.Errorf(`unexpected foreign-key "token_output_output_created_token_transaction" returned %v`, n.ID)
		}
		for i := range nodes {
			assign(nodes[i], n)
		}
	}
	return nil
}
func (toq *TokenOutputQuery) loadOutputSpentTokenTransaction(ctx context.Context, query *TokenTransactionQuery, nodes []*TokenOutput, init func(*TokenOutput), assign func(*TokenOutput, *TokenTransaction)) error {
	ids := make([]uuid.UUID, 0, len(nodes))
	nodeids := make(map[uuid.UUID][]*TokenOutput)
	for i := range nodes {
		if nodes[i].token_output_output_spent_token_transaction == nil {
			continue
		}
		fk := *nodes[i].token_output_output_spent_token_transaction
		if _, ok := nodeids[fk]; !ok {
			ids = append(ids, fk)
		}
		nodeids[fk] = append(nodeids[fk], nodes[i])
	}
	if len(ids) == 0 {
		return nil
	}
	query.Where(tokentransaction.IDIn(ids...))
	neighbors, err := query.All(ctx)
	if err != nil {
		return err
	}
	for _, n := range neighbors {
		nodes, ok := nodeids[n.ID]
		if !ok {
			return fmt.Errorf(`unexpected foreign-key "token_output_output_spent_token_transaction" returned %v`, n.ID)
		}
		for i := range nodes {
			assign(nodes[i], n)
		}
	}
	return nil
}
func (toq *TokenOutputQuery) loadOutputSpentStartedTokenTransactions(ctx context.Context, query *TokenTransactionQuery, nodes []*TokenOutput, init func(*TokenOutput), assign func(*TokenOutput, *TokenTransaction)) error {
	edgeIDs := make([]driver.Value, len(nodes))
	byID := make(map[uuid.UUID]*TokenOutput)
	nids := make(map[uuid.UUID]map[*TokenOutput]struct{})
	for i, node := range nodes {
		edgeIDs[i] = node.ID
		byID[node.ID] = node
		if init != nil {
			init(node)
		}
	}
	query.Where(func(s *sql.Selector) {
		joinT := sql.Table(tokenoutput.OutputSpentStartedTokenTransactionsTable)
		s.Join(joinT).On(s.C(tokentransaction.FieldID), joinT.C(tokenoutput.OutputSpentStartedTokenTransactionsPrimaryKey[1]))
		s.Where(sql.InValues(joinT.C(tokenoutput.OutputSpentStartedTokenTransactionsPrimaryKey[0]), edgeIDs...))
		columns := s.SelectedColumns()
		s.Select(joinT.C(tokenoutput.OutputSpentStartedTokenTransactionsPrimaryKey[0]))
		s.AppendSelect(columns...)
		s.SetDistinct(false)
	})
	if err := query.prepareQuery(ctx); err != nil {
		return err
	}
	qr := QuerierFunc(func(ctx context.Context, q Query) (Value, error) {
		return query.sqlAll(ctx, func(_ context.Context, spec *sqlgraph.QuerySpec) {
			assign := spec.Assign
			values := spec.ScanValues
			spec.ScanValues = func(columns []string) ([]any, error) {
				values, err := values(columns[1:])
				if err != nil {
					return nil, err
				}
				return append([]any{new(uuid.UUID)}, values...), nil
			}
			spec.Assign = func(columns []string, values []any) error {
				outValue := *values[0].(*uuid.UUID)
				inValue := *values[1].(*uuid.UUID)
				if nids[inValue] == nil {
					nids[inValue] = map[*TokenOutput]struct{}{byID[outValue]: {}}
					return assign(columns[1:], values[1:])
				}
				nids[inValue][byID[outValue]] = struct{}{}
				return nil
			}
		})
	})
	neighbors, err := withInterceptors[[]*TokenTransaction](ctx, query, qr, query.inters)
	if err != nil {
		return err
	}
	for _, n := range neighbors {
		nodes, ok := nids[n.ID]
		if !ok {
			return fmt.Errorf(`unexpected "output_spent_started_token_transactions" node returned %v`, n.ID)
		}
		for kn := range nodes {
			assign(kn, n)
		}
	}
	return nil
}
func (toq *TokenOutputQuery) loadTokenPartialRevocationSecretShares(ctx context.Context, query *TokenPartialRevocationSecretShareQuery, nodes []*TokenOutput, init func(*TokenOutput), assign func(*TokenOutput, *TokenPartialRevocationSecretShare)) error {
	fks := make([]driver.Value, 0, len(nodes))
	nodeids := make(map[uuid.UUID]*TokenOutput)
	for i := range nodes {
		fks = append(fks, nodes[i].ID)
		nodeids[nodes[i].ID] = nodes[i]
		if init != nil {
			init(nodes[i])
		}
	}
	query.withFKs = true
	query.Where(predicate.TokenPartialRevocationSecretShare(func(s *sql.Selector) {
		s.Where(sql.InValues(s.C(tokenoutput.TokenPartialRevocationSecretSharesColumn), fks...))
	}))
	neighbors, err := query.All(ctx)
	if err != nil {
		return err
	}
	for _, n := range neighbors {
		fk := n.token_output_token_partial_revocation_secret_shares
		if fk == nil {
			return fmt.Errorf(`foreign-key "token_output_token_partial_revocation_secret_shares" is nil for node %v`, n.ID)
		}
		node, ok := nodeids[*fk]
		if !ok {
			return fmt.Errorf(`unexpected referenced foreign-key "token_output_token_partial_revocation_secret_shares" returned %v for node %v`, *fk, n.ID)
		}
		assign(node, n)
	}
	return nil
}
func (toq *TokenOutputQuery) loadTokenCreate(ctx context.Context, query *TokenCreateQuery, nodes []*TokenOutput, init func(*TokenOutput), assign func(*TokenOutput, *TokenCreate)) error {
	ids := make([]uuid.UUID, 0, len(nodes))
	nodeids := make(map[uuid.UUID][]*TokenOutput)
	for i := range nodes {
		fk := nodes[i].TokenCreateID
		if _, ok := nodeids[fk]; !ok {
			ids = append(ids, fk)
		}
		nodeids[fk] = append(nodeids[fk], nodes[i])
	}
	if len(ids) == 0 {
		return nil
	}
	query.Where(tokencreate.IDIn(ids...))
	neighbors, err := query.All(ctx)
	if err != nil {
		return err
	}
	for _, n := range neighbors {
		nodes, ok := nodeids[n.ID]
		if !ok {
			return fmt.Errorf(`unexpected foreign-key "token_create_id" returned %v`, n.ID)
		}
		for i := range nodes {
			assign(nodes[i], n)
		}
	}
	return nil
}

func (toq *TokenOutputQuery) sqlCount(ctx context.Context) (int, error) {
	_spec := toq.querySpec()
	if len(toq.modifiers) > 0 {
		_spec.Modifiers = toq.modifiers
	}
	_spec.Node.Columns = toq.ctx.Fields
	if len(toq.ctx.Fields) > 0 {
		_spec.Unique = toq.ctx.Unique != nil && *toq.ctx.Unique
	}
	return sqlgraph.CountNodes(ctx, toq.driver, _spec)
}

func (toq *TokenOutputQuery) querySpec() *sqlgraph.QuerySpec {
	_spec := sqlgraph.NewQuerySpec(tokenoutput.Table, tokenoutput.Columns, sqlgraph.NewFieldSpec(tokenoutput.FieldID, field.TypeUUID))
	_spec.From = toq.sql
	if unique := toq.ctx.Unique; unique != nil {
		_spec.Unique = *unique
	} else if toq.path != nil {
		_spec.Unique = true
	}
	if fields := toq.ctx.Fields; len(fields) > 0 {
		_spec.Node.Columns = make([]string, 0, len(fields))
		_spec.Node.Columns = append(_spec.Node.Columns, tokenoutput.FieldID)
		for i := range fields {
			if fields[i] != tokenoutput.FieldID {
				_spec.Node.Columns = append(_spec.Node.Columns, fields[i])
			}
		}
		if toq.withTokenCreate != nil {
			_spec.Node.AddColumnOnce(tokenoutput.FieldTokenCreateID)
		}
	}
	if ps := toq.predicates; len(ps) > 0 {
		_spec.Predicate = func(selector *sql.Selector) {
			for i := range ps {
				ps[i](selector)
			}
		}
	}
	if limit := toq.ctx.Limit; limit != nil {
		_spec.Limit = *limit
	}
	if offset := toq.ctx.Offset; offset != nil {
		_spec.Offset = *offset
	}
	if ps := toq.order; len(ps) > 0 {
		_spec.Order = func(selector *sql.Selector) {
			for i := range ps {
				ps[i](selector)
			}
		}
	}
	return _spec
}

func (toq *TokenOutputQuery) sqlQuery(ctx context.Context) *sql.Selector {
	builder := sql.Dialect(toq.driver.Dialect())
	t1 := builder.Table(tokenoutput.Table)
	columns := toq.ctx.Fields
	if len(columns) == 0 {
		columns = tokenoutput.Columns
	}
	selector := builder.Select(t1.Columns(columns...)...).From(t1)
	if toq.sql != nil {
		selector = toq.sql
		selector.Select(selector.Columns(columns...)...)
	}
	if toq.ctx.Unique != nil && *toq.ctx.Unique {
		selector.Distinct()
	}
	for _, m := range toq.modifiers {
		m(selector)
	}
	for _, p := range toq.predicates {
		p(selector)
	}
	for _, p := range toq.order {
		p(selector)
	}
	if offset := toq.ctx.Offset; offset != nil {
		// limit is mandatory for offset clause. We start
		// with default value, and override it below if needed.
		selector.Offset(*offset).Limit(math.MaxInt32)
	}
	if limit := toq.ctx.Limit; limit != nil {
		selector.Limit(*limit)
	}
	return selector
}

// ForUpdate locks the selected rows against concurrent updates, and prevent them from being
// updated, deleted or "selected ... for update" by other sessions, until the transaction is
// either committed or rolled-back.
func (toq *TokenOutputQuery) ForUpdate(opts ...sql.LockOption) *TokenOutputQuery {
	if toq.driver.Dialect() == dialect.Postgres {
		toq.Unique(false)
	}
	toq.modifiers = append(toq.modifiers, func(s *sql.Selector) {
		s.ForUpdate(opts...)
	})
	return toq
}

// ForShare behaves similarly to ForUpdate, except that it acquires a shared mode lock
// on any rows that are read. Other sessions can read the rows, but cannot modify them
// until your transaction commits.
func (toq *TokenOutputQuery) ForShare(opts ...sql.LockOption) *TokenOutputQuery {
	if toq.driver.Dialect() == dialect.Postgres {
		toq.Unique(false)
	}
	toq.modifiers = append(toq.modifiers, func(s *sql.Selector) {
		s.ForShare(opts...)
	})
	return toq
}

// TokenOutputGroupBy is the group-by builder for TokenOutput entities.
type TokenOutputGroupBy struct {
	selector
	build *TokenOutputQuery
}

// Aggregate adds the given aggregation functions to the group-by query.
func (togb *TokenOutputGroupBy) Aggregate(fns ...AggregateFunc) *TokenOutputGroupBy {
	togb.fns = append(togb.fns, fns...)
	return togb
}

// Scan applies the selector query and scans the result into the given value.
func (togb *TokenOutputGroupBy) Scan(ctx context.Context, v any) error {
	ctx = setContextOp(ctx, togb.build.ctx, ent.OpQueryGroupBy)
	if err := togb.build.prepareQuery(ctx); err != nil {
		return err
	}
	return scanWithInterceptors[*TokenOutputQuery, *TokenOutputGroupBy](ctx, togb.build, togb, togb.build.inters, v)
}

func (togb *TokenOutputGroupBy) sqlScan(ctx context.Context, root *TokenOutputQuery, v any) error {
	selector := root.sqlQuery(ctx).Select()
	aggregation := make([]string, 0, len(togb.fns))
	for _, fn := range togb.fns {
		aggregation = append(aggregation, fn(selector))
	}
	if len(selector.SelectedColumns()) == 0 {
		columns := make([]string, 0, len(*togb.flds)+len(togb.fns))
		for _, f := range *togb.flds {
			columns = append(columns, selector.C(f))
		}
		columns = append(columns, aggregation...)
		selector.Select(columns...)
	}
	selector.GroupBy(selector.Columns(*togb.flds...)...)
	if err := selector.Err(); err != nil {
		return err
	}
	rows := &sql.Rows{}
	query, args := selector.Query()
	if err := togb.build.driver.Query(ctx, query, args, rows); err != nil {
		return err
	}
	defer rows.Close()
	return sql.ScanSlice(rows, v)
}

// TokenOutputSelect is the builder for selecting fields of TokenOutput entities.
type TokenOutputSelect struct {
	*TokenOutputQuery
	selector
}

// Aggregate adds the given aggregation functions to the selector query.
func (tos *TokenOutputSelect) Aggregate(fns ...AggregateFunc) *TokenOutputSelect {
	tos.fns = append(tos.fns, fns...)
	return tos
}

// Scan applies the selector query and scans the result into the given value.
func (tos *TokenOutputSelect) Scan(ctx context.Context, v any) error {
	ctx = setContextOp(ctx, tos.ctx, ent.OpQuerySelect)
	if err := tos.prepareQuery(ctx); err != nil {
		return err
	}
	return scanWithInterceptors[*TokenOutputQuery, *TokenOutputSelect](ctx, tos.TokenOutputQuery, tos, tos.inters, v)
}

func (tos *TokenOutputSelect) sqlScan(ctx context.Context, root *TokenOutputQuery, v any) error {
	selector := root.sqlQuery(ctx)
	aggregation := make([]string, 0, len(tos.fns))
	for _, fn := range tos.fns {
		aggregation = append(aggregation, fn(selector))
	}
	switch n := len(*tos.selector.flds); {
	case n == 0 && len(aggregation) > 0:
		selector.Select(aggregation...)
	case n != 0 && len(aggregation) > 0:
		selector.AppendSelect(aggregation...)
	}
	rows := &sql.Rows{}
	query, args := selector.Query()
	if err := tos.driver.Query(ctx, query, args, rows); err != nil {
		return err
	}
	defer rows.Close()
	return sql.ScanSlice(rows, v)
}
