// Code generated by ent, DO NOT EDIT.

package ent

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

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

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

// Where adds a new predicate for the XunjiServiceQuery builder.
func (xsq *XunjiServiceQuery) Where(ps ...predicate.XunjiService) *XunjiServiceQuery {
	xsq.predicates = append(xsq.predicates, ps...)
	return xsq
}

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

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

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

// Order specifies how the records should be ordered.
func (xsq *XunjiServiceQuery) Order(o ...xunjiservice.OrderOption) *XunjiServiceQuery {
	xsq.order = append(xsq.order, o...)
	return xsq
}

// QueryAgent chains the current query on the "agent" edge.
func (xsq *XunjiServiceQuery) QueryAgent() *AgentQuery {
	query := (&AgentClient{config: xsq.config}).Query()
	query.path = func(ctx context.Context) (fromU *sql.Selector, err error) {
		if err := xsq.prepareQuery(ctx); err != nil {
			return nil, err
		}
		selector := xsq.sqlQuery(ctx)
		if err := selector.Err(); err != nil {
			return nil, err
		}
		step := sqlgraph.NewStep(
			sqlgraph.From(xunjiservice.Table, xunjiservice.FieldID, selector),
			sqlgraph.To(agent.Table, agent.FieldID),
			sqlgraph.Edge(sqlgraph.M2O, true, xunjiservice.AgentTable, xunjiservice.AgentColumn),
		)
		fromU = sqlgraph.SetNeighbors(xsq.driver.Dialect(), step)
		return fromU, nil
	}
	return query
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

// WithAgent tells the query-builder to eager-load the nodes that are connected to
// the "agent" edge. The optional arguments are used to configure the query builder of the edge.
func (xsq *XunjiServiceQuery) WithAgent(opts ...func(*AgentQuery)) *XunjiServiceQuery {
	query := (&AgentClient{config: xsq.config}).Query()
	for _, opt := range opts {
		opt(query)
	}
	xsq.withAgent = query
	return xsq
}

// 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.XunjiService.Query().
//		GroupBy(xunjiservice.FieldCreatedAt).
//		Aggregate(ent.Count()).
//		Scan(ctx, &v)
func (xsq *XunjiServiceQuery) GroupBy(field string, fields ...string) *XunjiServiceGroupBy {
	xsq.ctx.Fields = append([]string{field}, fields...)
	grbuild := &XunjiServiceGroupBy{build: xsq}
	grbuild.flds = &xsq.ctx.Fields
	grbuild.label = xunjiservice.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.XunjiService.Query().
//		Select(xunjiservice.FieldCreatedAt).
//		Scan(ctx, &v)
func (xsq *XunjiServiceQuery) Select(fields ...string) *XunjiServiceSelect {
	xsq.ctx.Fields = append(xsq.ctx.Fields, fields...)
	sbuild := &XunjiServiceSelect{XunjiServiceQuery: xsq}
	sbuild.label = xunjiservice.Label
	sbuild.flds, sbuild.scan = &xsq.ctx.Fields, sbuild.Scan
	return sbuild
}

// Aggregate returns a XunjiServiceSelect configured with the given aggregations.
func (xsq *XunjiServiceQuery) Aggregate(fns ...AggregateFunc) *XunjiServiceSelect {
	return xsq.Select().Aggregate(fns...)
}

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

func (xsq *XunjiServiceQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*XunjiService, error) {
	var (
		nodes       = []*XunjiService{}
		_spec       = xsq.querySpec()
		loadedTypes = [1]bool{
			xsq.withAgent != nil,
		}
	)
	_spec.ScanValues = func(columns []string) ([]any, error) {
		return (*XunjiService).scanValues(nil, columns)
	}
	_spec.Assign = func(columns []string, values []any) error {
		node := &XunjiService{config: xsq.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, xsq.driver, _spec); err != nil {
		return nil, err
	}
	if len(nodes) == 0 {
		return nodes, nil
	}
	if query := xsq.withAgent; query != nil {
		if err := xsq.loadAgent(ctx, query, nodes, nil,
			func(n *XunjiService, e *Agent) { n.Edges.Agent = e }); err != nil {
			return nil, err
		}
	}
	return nodes, nil
}

func (xsq *XunjiServiceQuery) loadAgent(ctx context.Context, query *AgentQuery, nodes []*XunjiService, init func(*XunjiService), assign func(*XunjiService, *Agent)) error {
	ids := make([]uint64, 0, len(nodes))
	nodeids := make(map[uint64][]*XunjiService)
	for i := range nodes {
		fk := nodes[i].AgentID
		if _, ok := nodeids[fk]; !ok {
			ids = append(ids, fk)
		}
		nodeids[fk] = append(nodeids[fk], nodes[i])
	}
	if len(ids) == 0 {
		return nil
	}
	query.Where(agent.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 "agent_id" returned %v`, n.ID)
		}
		for i := range nodes {
			assign(nodes[i], n)
		}
	}
	return nil
}

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

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

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

// XunjiServiceGroupBy is the group-by builder for XunjiService entities.
type XunjiServiceGroupBy struct {
	selector
	build *XunjiServiceQuery
}

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

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

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

// XunjiServiceSelect is the builder for selecting fields of XunjiService entities.
type XunjiServiceSelect struct {
	*XunjiServiceQuery
	selector
}

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

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

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