// Code generated by ent, DO NOT EDIT.

package ent

import (
	"context"
	"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/pendingsendtransfer"
	"github.com/lightsparkdev/spark/so/ent/predicate"
)

// PendingSendTransferQuery is the builder for querying PendingSendTransfer entities.
type PendingSendTransferQuery struct {
	config
	ctx        *QueryContext
	order      []pendingsendtransfer.OrderOption
	inters     []Interceptor
	predicates []predicate.PendingSendTransfer
	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 PendingSendTransferQuery builder.
func (pstq *PendingSendTransferQuery) Where(ps ...predicate.PendingSendTransfer) *PendingSendTransferQuery {
	pstq.predicates = append(pstq.predicates, ps...)
	return pstq
}

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

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

// 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 (pstq *PendingSendTransferQuery) Unique(unique bool) *PendingSendTransferQuery {
	pstq.ctx.Unique = &unique
	return pstq
}

// Order specifies how the records should be ordered.
func (pstq *PendingSendTransferQuery) Order(o ...pendingsendtransfer.OrderOption) *PendingSendTransferQuery {
	pstq.order = append(pstq.order, o...)
	return pstq
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

// Exist returns true if the query has elements in the graph.
func (pstq *PendingSendTransferQuery) Exist(ctx context.Context) (bool, error) {
	ctx = setContextOp(ctx, pstq.ctx, ent.OpQueryExist)
	switch _, err := pstq.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 (pstq *PendingSendTransferQuery) ExistX(ctx context.Context) bool {
	exist, err := pstq.Exist(ctx)
	if err != nil {
		panic(err)
	}
	return exist
}

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

// 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.PendingSendTransfer.Query().
//		GroupBy(pendingsendtransfer.FieldCreateTime).
//		Aggregate(ent.Count()).
//		Scan(ctx, &v)
func (pstq *PendingSendTransferQuery) GroupBy(field string, fields ...string) *PendingSendTransferGroupBy {
	pstq.ctx.Fields = append([]string{field}, fields...)
	grbuild := &PendingSendTransferGroupBy{build: pstq}
	grbuild.flds = &pstq.ctx.Fields
	grbuild.label = pendingsendtransfer.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.PendingSendTransfer.Query().
//		Select(pendingsendtransfer.FieldCreateTime).
//		Scan(ctx, &v)
func (pstq *PendingSendTransferQuery) Select(fields ...string) *PendingSendTransferSelect {
	pstq.ctx.Fields = append(pstq.ctx.Fields, fields...)
	sbuild := &PendingSendTransferSelect{PendingSendTransferQuery: pstq}
	sbuild.label = pendingsendtransfer.Label
	sbuild.flds, sbuild.scan = &pstq.ctx.Fields, sbuild.Scan
	return sbuild
}

// Aggregate returns a PendingSendTransferSelect configured with the given aggregations.
func (pstq *PendingSendTransferQuery) Aggregate(fns ...AggregateFunc) *PendingSendTransferSelect {
	return pstq.Select().Aggregate(fns...)
}

func (pstq *PendingSendTransferQuery) prepareQuery(ctx context.Context) error {
	for _, inter := range pstq.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, pstq); err != nil {
				return err
			}
		}
	}
	for _, f := range pstq.ctx.Fields {
		if !pendingsendtransfer.ValidColumn(f) {
			return &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)}
		}
	}
	if pstq.path != nil {
		prev, err := pstq.path(ctx)
		if err != nil {
			return err
		}
		pstq.sql = prev
	}
	return nil
}

func (pstq *PendingSendTransferQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*PendingSendTransfer, error) {
	var (
		nodes = []*PendingSendTransfer{}
		_spec = pstq.querySpec()
	)
	_spec.ScanValues = func(columns []string) ([]any, error) {
		return (*PendingSendTransfer).scanValues(nil, columns)
	}
	_spec.Assign = func(columns []string, values []any) error {
		node := &PendingSendTransfer{config: pstq.config}
		nodes = append(nodes, node)
		return node.assignValues(columns, values)
	}
	if len(pstq.modifiers) > 0 {
		_spec.Modifiers = pstq.modifiers
	}
	for i := range hooks {
		hooks[i](ctx, _spec)
	}
	if err := sqlgraph.QueryNodes(ctx, pstq.driver, _spec); err != nil {
		return nil, err
	}
	if len(nodes) == 0 {
		return nodes, nil
	}
	return nodes, nil
}

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

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

func (pstq *PendingSendTransferQuery) sqlQuery(ctx context.Context) *sql.Selector {
	builder := sql.Dialect(pstq.driver.Dialect())
	t1 := builder.Table(pendingsendtransfer.Table)
	columns := pstq.ctx.Fields
	if len(columns) == 0 {
		columns = pendingsendtransfer.Columns
	}
	selector := builder.Select(t1.Columns(columns...)...).From(t1)
	if pstq.sql != nil {
		selector = pstq.sql
		selector.Select(selector.Columns(columns...)...)
	}
	if pstq.ctx.Unique != nil && *pstq.ctx.Unique {
		selector.Distinct()
	}
	for _, m := range pstq.modifiers {
		m(selector)
	}
	for _, p := range pstq.predicates {
		p(selector)
	}
	for _, p := range pstq.order {
		p(selector)
	}
	if offset := pstq.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 := pstq.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 (pstq *PendingSendTransferQuery) ForUpdate(opts ...sql.LockOption) *PendingSendTransferQuery {
	if pstq.driver.Dialect() == dialect.Postgres {
		pstq.Unique(false)
	}
	pstq.modifiers = append(pstq.modifiers, func(s *sql.Selector) {
		s.ForUpdate(opts...)
	})
	return pstq
}

// 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 (pstq *PendingSendTransferQuery) ForShare(opts ...sql.LockOption) *PendingSendTransferQuery {
	if pstq.driver.Dialect() == dialect.Postgres {
		pstq.Unique(false)
	}
	pstq.modifiers = append(pstq.modifiers, func(s *sql.Selector) {
		s.ForShare(opts...)
	})
	return pstq
}

// PendingSendTransferGroupBy is the group-by builder for PendingSendTransfer entities.
type PendingSendTransferGroupBy struct {
	selector
	build *PendingSendTransferQuery
}

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

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

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

// PendingSendTransferSelect is the builder for selecting fields of PendingSendTransfer entities.
type PendingSendTransferSelect struct {
	*PendingSendTransferQuery
	selector
}

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

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

func (psts *PendingSendTransferSelect) sqlScan(ctx context.Context, root *PendingSendTransferQuery, v any) error {
	selector := root.sqlQuery(ctx)
	aggregation := make([]string, 0, len(psts.fns))
	for _, fn := range psts.fns {
		aggregation = append(aggregation, fn(selector))
	}
	switch n := len(*psts.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 := psts.driver.Query(ctx, query, args, rows); err != nil {
		return err
	}
	defer rows.Close()
	return sql.ScanSlice(rows, v)
}
