// Code generated by ent, DO NOT EDIT.

package ent

import (
	"context"
	"database/sql/driver"
	"fmt"
	"math"
	"wechat-api/ent/agentbase"
	"wechat-api/ent/predicate"
	"wechat-api/ent/wx"

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

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

// Where adds a new predicate for the AgentBaseQuery builder.
func (abq *AgentBaseQuery) Where(ps ...predicate.AgentBase) *AgentBaseQuery {
	abq.predicates = append(abq.predicates, ps...)
	return abq
}

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

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

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

// Order specifies how the records should be ordered.
func (abq *AgentBaseQuery) Order(o ...agentbase.OrderOption) *AgentBaseQuery {
	abq.order = append(abq.order, o...)
	return abq
}

// QueryWxAgent chains the current query on the "wx_agent" edge.
func (abq *AgentBaseQuery) QueryWxAgent() *WxQuery {
	query := (&WxClient{config: abq.config}).Query()
	query.path = func(ctx context.Context) (fromU *sql.Selector, err error) {
		if err := abq.prepareQuery(ctx); err != nil {
			return nil, err
		}
		selector := abq.sqlQuery(ctx)
		if err := selector.Err(); err != nil {
			return nil, err
		}
		step := sqlgraph.NewStep(
			sqlgraph.From(agentbase.Table, agentbase.FieldID, selector),
			sqlgraph.To(wx.Table, wx.FieldID),
			sqlgraph.Edge(sqlgraph.O2M, false, agentbase.WxAgentTable, agentbase.WxAgentColumn),
		)
		fromU = sqlgraph.SetNeighbors(abq.driver.Dialect(), step)
		return fromU, nil
	}
	return query
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

// WithWxAgent tells the query-builder to eager-load the nodes that are connected to
// the "wx_agent" edge. The optional arguments are used to configure the query builder of the edge.
func (abq *AgentBaseQuery) WithWxAgent(opts ...func(*WxQuery)) *AgentBaseQuery {
	query := (&WxClient{config: abq.config}).Query()
	for _, opt := range opts {
		opt(query)
	}
	abq.withWxAgent = query
	return abq
}

// 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 {
//		Q string `json:"q,omitempty"`
//		Count int `json:"count,omitempty"`
//	}
//
//	client.AgentBase.Query().
//		GroupBy(agentbase.FieldQ).
//		Aggregate(ent.Count()).
//		Scan(ctx, &v)
func (abq *AgentBaseQuery) GroupBy(field string, fields ...string) *AgentBaseGroupBy {
	abq.ctx.Fields = append([]string{field}, fields...)
	grbuild := &AgentBaseGroupBy{build: abq}
	grbuild.flds = &abq.ctx.Fields
	grbuild.label = agentbase.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 {
//		Q string `json:"q,omitempty"`
//	}
//
//	client.AgentBase.Query().
//		Select(agentbase.FieldQ).
//		Scan(ctx, &v)
func (abq *AgentBaseQuery) Select(fields ...string) *AgentBaseSelect {
	abq.ctx.Fields = append(abq.ctx.Fields, fields...)
	sbuild := &AgentBaseSelect{AgentBaseQuery: abq}
	sbuild.label = agentbase.Label
	sbuild.flds, sbuild.scan = &abq.ctx.Fields, sbuild.Scan
	return sbuild
}

// Aggregate returns a AgentBaseSelect configured with the given aggregations.
func (abq *AgentBaseQuery) Aggregate(fns ...AggregateFunc) *AgentBaseSelect {
	return abq.Select().Aggregate(fns...)
}

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

func (abq *AgentBaseQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*AgentBase, error) {
	var (
		nodes       = []*AgentBase{}
		_spec       = abq.querySpec()
		loadedTypes = [1]bool{
			abq.withWxAgent != nil,
		}
	)
	_spec.ScanValues = func(columns []string) ([]any, error) {
		return (*AgentBase).scanValues(nil, columns)
	}
	_spec.Assign = func(columns []string, values []any) error {
		node := &AgentBase{config: abq.config}
		nodes = append(nodes, node)
		node.Edges.loadedTypes = loadedTypes
		return node.assignValues(columns, values)
	}
	for i := range hooks {
		hooks[i](ctx, _spec)
	}
	if err := sqlgraph.QueryNodes(ctx, abq.driver, _spec); err != nil {
		return nil, err
	}
	if len(nodes) == 0 {
		return nodes, nil
	}
	if query := abq.withWxAgent; query != nil {
		if err := abq.loadWxAgent(ctx, query, nodes,
			func(n *AgentBase) { n.Edges.WxAgent = []*Wx{} },
			func(n *AgentBase, e *Wx) { n.Edges.WxAgent = append(n.Edges.WxAgent, e) }); err != nil {
			return nil, err
		}
	}
	return nodes, nil
}

func (abq *AgentBaseQuery) loadWxAgent(ctx context.Context, query *WxQuery, nodes []*AgentBase, init func(*AgentBase), assign func(*AgentBase, *Wx)) error {
	fks := make([]driver.Value, 0, len(nodes))
	nodeids := make(map[string]*AgentBase)
	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.Wx(func(s *sql.Selector) {
		s.Where(sql.InValues(s.C(agentbase.WxAgentColumn), fks...))
	}))
	neighbors, err := query.All(ctx)
	if err != nil {
		return err
	}
	for _, n := range neighbors {
		fk := n.agent_base_wx_agent
		if fk == nil {
			return fmt.Errorf(`foreign-key "agent_base_wx_agent" is nil for node %v`, n.ID)
		}
		node, ok := nodeids[*fk]
		if !ok {
			return fmt.Errorf(`unexpected referenced foreign-key "agent_base_wx_agent" returned %v for node %v`, *fk, n.ID)
		}
		assign(node, n)
	}
	return nil
}

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

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

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

// AgentBaseGroupBy is the group-by builder for AgentBase entities.
type AgentBaseGroupBy struct {
	selector
	build *AgentBaseQuery
}

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

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

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

// AgentBaseSelect is the builder for selecting fields of AgentBase entities.
type AgentBaseSelect struct {
	*AgentBaseQuery
	selector
}

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

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

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