// Code generated by ent, DO NOT EDIT.

package ent

import (
	"context"
	"fmt"
	"math"
	"wechat-api/ent/allocagent"
	"wechat-api/ent/predicate"

	"entgo.io/ent/dialect/sql"
	"entgo.io/ent/dialect/sql/sqlgraph"
	"entgo.io/ent/schema/field"
)

// AllocAgentQuery is the builder for querying AllocAgent entities.
type AllocAgentQuery struct {
	config
	ctx        *QueryContext
	order      []allocagent.OrderOption
	inters     []Interceptor
	predicates []predicate.AllocAgent
	// intermediate query (i.e. traversal path).
	sql  *sql.Selector
	path func(context.Context) (*sql.Selector, error)
}

// Where adds a new predicate for the AllocAgentQuery builder.
func (aaq *AllocAgentQuery) Where(ps ...predicate.AllocAgent) *AllocAgentQuery {
	aaq.predicates = append(aaq.predicates, ps...)
	return aaq
}

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

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

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

// Order specifies how the records should be ordered.
func (aaq *AllocAgentQuery) Order(o ...allocagent.OrderOption) *AllocAgentQuery {
	aaq.order = append(aaq.order, o...)
	return aaq
}

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

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

// FirstID returns the first AllocAgent ID from the query.
// Returns a *NotFoundError when no AllocAgent ID was found.
func (aaq *AllocAgentQuery) FirstID(ctx context.Context) (id uint64, err error) {
	var ids []uint64
	if ids, err = aaq.Limit(1).IDs(setContextOp(ctx, aaq.ctx, "FirstID")); err != nil {
		return
	}
	if len(ids) == 0 {
		err = &NotFoundError{allocagent.Label}
		return
	}
	return ids[0], nil
}

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

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

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

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

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

// All executes the query and returns a list of AllocAgents.
func (aaq *AllocAgentQuery) All(ctx context.Context) ([]*AllocAgent, error) {
	ctx = setContextOp(ctx, aaq.ctx, "All")
	if err := aaq.prepareQuery(ctx); err != nil {
		return nil, err
	}
	qr := querierAll[[]*AllocAgent, *AllocAgentQuery]()
	return withInterceptors[[]*AllocAgent](ctx, aaq, qr, aaq.inters)
}

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

// IDs executes the query and returns a list of AllocAgent IDs.
func (aaq *AllocAgentQuery) IDs(ctx context.Context) (ids []uint64, err error) {
	if aaq.ctx.Unique == nil && aaq.path != nil {
		aaq.Unique(true)
	}
	ctx = setContextOp(ctx, aaq.ctx, "IDs")
	if err = aaq.Select(allocagent.FieldID).Scan(ctx, &ids); err != nil {
		return nil, err
	}
	return ids, nil
}

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

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

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

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

// Clone returns a duplicate of the AllocAgentQuery builder, including all associated steps. It can be
// used to prepare common query builders and use them differently after the clone is made.
func (aaq *AllocAgentQuery) Clone() *AllocAgentQuery {
	if aaq == nil {
		return nil
	}
	return &AllocAgentQuery{
		config:     aaq.config,
		ctx:        aaq.ctx.Clone(),
		order:      append([]allocagent.OrderOption{}, aaq.order...),
		inters:     append([]Interceptor{}, aaq.inters...),
		predicates: append([]predicate.AllocAgent{}, aaq.predicates...),
		// clone intermediate query.
		sql:  aaq.sql.Clone(),
		path: aaq.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 {
//		CreatedAt time.Time `json:"created_at,omitempty"`
//		Count int `json:"count,omitempty"`
//	}
//
//	client.AllocAgent.Query().
//		GroupBy(allocagent.FieldCreatedAt).
//		Aggregate(ent.Count()).
//		Scan(ctx, &v)
func (aaq *AllocAgentQuery) GroupBy(field string, fields ...string) *AllocAgentGroupBy {
	aaq.ctx.Fields = append([]string{field}, fields...)
	grbuild := &AllocAgentGroupBy{build: aaq}
	grbuild.flds = &aaq.ctx.Fields
	grbuild.label = allocagent.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 {
//		CreatedAt time.Time `json:"created_at,omitempty"`
//	}
//
//	client.AllocAgent.Query().
//		Select(allocagent.FieldCreatedAt).
//		Scan(ctx, &v)
func (aaq *AllocAgentQuery) Select(fields ...string) *AllocAgentSelect {
	aaq.ctx.Fields = append(aaq.ctx.Fields, fields...)
	sbuild := &AllocAgentSelect{AllocAgentQuery: aaq}
	sbuild.label = allocagent.Label
	sbuild.flds, sbuild.scan = &aaq.ctx.Fields, sbuild.Scan
	return sbuild
}

// Aggregate returns a AllocAgentSelect configured with the given aggregations.
func (aaq *AllocAgentQuery) Aggregate(fns ...AggregateFunc) *AllocAgentSelect {
	return aaq.Select().Aggregate(fns...)
}

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

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

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

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

func (aaq *AllocAgentQuery) sqlQuery(ctx context.Context) *sql.Selector {
	builder := sql.Dialect(aaq.driver.Dialect())
	t1 := builder.Table(allocagent.Table)
	columns := aaq.ctx.Fields
	if len(columns) == 0 {
		columns = allocagent.Columns
	}
	selector := builder.Select(t1.Columns(columns...)...).From(t1)
	if aaq.sql != nil {
		selector = aaq.sql
		selector.Select(selector.Columns(columns...)...)
	}
	if aaq.ctx.Unique != nil && *aaq.ctx.Unique {
		selector.Distinct()
	}
	for _, p := range aaq.predicates {
		p(selector)
	}
	for _, p := range aaq.order {
		p(selector)
	}
	if offset := aaq.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 := aaq.ctx.Limit; limit != nil {
		selector.Limit(*limit)
	}
	return selector
}

// AllocAgentGroupBy is the group-by builder for AllocAgent entities.
type AllocAgentGroupBy struct {
	selector
	build *AllocAgentQuery
}

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

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

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

// AllocAgentSelect is the builder for selecting fields of AllocAgent entities.
type AllocAgentSelect struct {
	*AllocAgentQuery
	selector
}

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

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

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