// Code generated by ent, DO NOT EDIT.

package ent

import (
	"context"
	"database/sql/driver"
	"fmt"
	"math"
	"wechat-api/ent/messagerecords"
	"wechat-api/ent/predicate"
	"wechat-api/ent/sopnode"
	"wechat-api/ent/sopstage"

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

// SopNodeQuery is the builder for querying SopNode entities.
type SopNodeQuery struct {
	config
	ctx              *QueryContext
	order            []sopnode.OrderOption
	inters           []Interceptor
	predicates       []predicate.SopNode
	withSopStage     *SopStageQuery
	withNodeMessages *MessageRecordsQuery
	// intermediate query (i.e. traversal path).
	sql  *sql.Selector
	path func(context.Context) (*sql.Selector, error)
}

// Where adds a new predicate for the SopNodeQuery builder.
func (snq *SopNodeQuery) Where(ps ...predicate.SopNode) *SopNodeQuery {
	snq.predicates = append(snq.predicates, ps...)
	return snq
}

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

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

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

// Order specifies how the records should be ordered.
func (snq *SopNodeQuery) Order(o ...sopnode.OrderOption) *SopNodeQuery {
	snq.order = append(snq.order, o...)
	return snq
}

// QuerySopStage chains the current query on the "sop_stage" edge.
func (snq *SopNodeQuery) QuerySopStage() *SopStageQuery {
	query := (&SopStageClient{config: snq.config}).Query()
	query.path = func(ctx context.Context) (fromU *sql.Selector, err error) {
		if err := snq.prepareQuery(ctx); err != nil {
			return nil, err
		}
		selector := snq.sqlQuery(ctx)
		if err := selector.Err(); err != nil {
			return nil, err
		}
		step := sqlgraph.NewStep(
			sqlgraph.From(sopnode.Table, sopnode.FieldID, selector),
			sqlgraph.To(sopstage.Table, sopstage.FieldID),
			sqlgraph.Edge(sqlgraph.M2O, true, sopnode.SopStageTable, sopnode.SopStageColumn),
		)
		fromU = sqlgraph.SetNeighbors(snq.driver.Dialect(), step)
		return fromU, nil
	}
	return query
}

// QueryNodeMessages chains the current query on the "node_messages" edge.
func (snq *SopNodeQuery) QueryNodeMessages() *MessageRecordsQuery {
	query := (&MessageRecordsClient{config: snq.config}).Query()
	query.path = func(ctx context.Context) (fromU *sql.Selector, err error) {
		if err := snq.prepareQuery(ctx); err != nil {
			return nil, err
		}
		selector := snq.sqlQuery(ctx)
		if err := selector.Err(); err != nil {
			return nil, err
		}
		step := sqlgraph.NewStep(
			sqlgraph.From(sopnode.Table, sopnode.FieldID, selector),
			sqlgraph.To(messagerecords.Table, messagerecords.FieldID),
			sqlgraph.Edge(sqlgraph.O2M, false, sopnode.NodeMessagesTable, sopnode.NodeMessagesColumn),
		)
		fromU = sqlgraph.SetNeighbors(snq.driver.Dialect(), step)
		return fromU, nil
	}
	return query
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

// WithSopStage tells the query-builder to eager-load the nodes that are connected to
// the "sop_stage" edge. The optional arguments are used to configure the query builder of the edge.
func (snq *SopNodeQuery) WithSopStage(opts ...func(*SopStageQuery)) *SopNodeQuery {
	query := (&SopStageClient{config: snq.config}).Query()
	for _, opt := range opts {
		opt(query)
	}
	snq.withSopStage = query
	return snq
}

// WithNodeMessages tells the query-builder to eager-load the nodes that are connected to
// the "node_messages" edge. The optional arguments are used to configure the query builder of the edge.
func (snq *SopNodeQuery) WithNodeMessages(opts ...func(*MessageRecordsQuery)) *SopNodeQuery {
	query := (&MessageRecordsClient{config: snq.config}).Query()
	for _, opt := range opts {
		opt(query)
	}
	snq.withNodeMessages = query
	return snq
}

// 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.SopNode.Query().
//		GroupBy(sopnode.FieldCreatedAt).
//		Aggregate(ent.Count()).
//		Scan(ctx, &v)
func (snq *SopNodeQuery) GroupBy(field string, fields ...string) *SopNodeGroupBy {
	snq.ctx.Fields = append([]string{field}, fields...)
	grbuild := &SopNodeGroupBy{build: snq}
	grbuild.flds = &snq.ctx.Fields
	grbuild.label = sopnode.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.SopNode.Query().
//		Select(sopnode.FieldCreatedAt).
//		Scan(ctx, &v)
func (snq *SopNodeQuery) Select(fields ...string) *SopNodeSelect {
	snq.ctx.Fields = append(snq.ctx.Fields, fields...)
	sbuild := &SopNodeSelect{SopNodeQuery: snq}
	sbuild.label = sopnode.Label
	sbuild.flds, sbuild.scan = &snq.ctx.Fields, sbuild.Scan
	return sbuild
}

// Aggregate returns a SopNodeSelect configured with the given aggregations.
func (snq *SopNodeQuery) Aggregate(fns ...AggregateFunc) *SopNodeSelect {
	return snq.Select().Aggregate(fns...)
}

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

func (snq *SopNodeQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*SopNode, error) {
	var (
		nodes       = []*SopNode{}
		_spec       = snq.querySpec()
		loadedTypes = [2]bool{
			snq.withSopStage != nil,
			snq.withNodeMessages != nil,
		}
	)
	_spec.ScanValues = func(columns []string) ([]any, error) {
		return (*SopNode).scanValues(nil, columns)
	}
	_spec.Assign = func(columns []string, values []any) error {
		node := &SopNode{config: snq.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, snq.driver, _spec); err != nil {
		return nil, err
	}
	if len(nodes) == 0 {
		return nodes, nil
	}
	if query := snq.withSopStage; query != nil {
		if err := snq.loadSopStage(ctx, query, nodes, nil,
			func(n *SopNode, e *SopStage) { n.Edges.SopStage = e }); err != nil {
			return nil, err
		}
	}
	if query := snq.withNodeMessages; query != nil {
		if err := snq.loadNodeMessages(ctx, query, nodes,
			func(n *SopNode) { n.Edges.NodeMessages = []*MessageRecords{} },
			func(n *SopNode, e *MessageRecords) { n.Edges.NodeMessages = append(n.Edges.NodeMessages, e) }); err != nil {
			return nil, err
		}
	}
	return nodes, nil
}

func (snq *SopNodeQuery) loadSopStage(ctx context.Context, query *SopStageQuery, nodes []*SopNode, init func(*SopNode), assign func(*SopNode, *SopStage)) error {
	ids := make([]uint64, 0, len(nodes))
	nodeids := make(map[uint64][]*SopNode)
	for i := range nodes {
		fk := nodes[i].StageID
		if _, ok := nodeids[fk]; !ok {
			ids = append(ids, fk)
		}
		nodeids[fk] = append(nodeids[fk], nodes[i])
	}
	if len(ids) == 0 {
		return nil
	}
	query.Where(sopstage.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 "stage_id" returned %v`, n.ID)
		}
		for i := range nodes {
			assign(nodes[i], n)
		}
	}
	return nil
}
func (snq *SopNodeQuery) loadNodeMessages(ctx context.Context, query *MessageRecordsQuery, nodes []*SopNode, init func(*SopNode), assign func(*SopNode, *MessageRecords)) error {
	fks := make([]driver.Value, 0, len(nodes))
	nodeids := make(map[uint64]*SopNode)
	for i := range nodes {
		fks = append(fks, nodes[i].ID)
		nodeids[nodes[i].ID] = nodes[i]
		if init != nil {
			init(nodes[i])
		}
	}
	if len(query.ctx.Fields) > 0 {
		query.ctx.AppendFieldOnce(messagerecords.FieldSubSourceID)
	}
	query.Where(predicate.MessageRecords(func(s *sql.Selector) {
		s.Where(sql.InValues(s.C(sopnode.NodeMessagesColumn), fks...))
	}))
	neighbors, err := query.All(ctx)
	if err != nil {
		return err
	}
	for _, n := range neighbors {
		fk := n.SubSourceID
		node, ok := nodeids[fk]
		if !ok {
			return fmt.Errorf(`unexpected referenced foreign-key "sub_source_id" returned %v for node %v`, fk, n.ID)
		}
		assign(node, n)
	}
	return nil
}

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

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

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

// SopNodeGroupBy is the group-by builder for SopNode entities.
type SopNodeGroupBy struct {
	selector
	build *SopNodeQuery
}

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

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

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

// SopNodeSelect is the builder for selecting fields of SopNode entities.
type SopNodeSelect struct {
	*SopNodeQuery
	selector
}

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

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

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