// Code generated by ent, DO NOT EDIT.

package ent

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

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

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

// Where adds a new predicate for the XunjiQuery builder.
func (xq *XunjiQuery) Where(ps ...predicate.Xunji) *XunjiQuery {
	xq.predicates = append(xq.predicates, ps...)
	return xq
}

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

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

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

// Order specifies how the records should be ordered.
func (xq *XunjiQuery) Order(o ...xunji.OrderOption) *XunjiQuery {
	xq.order = append(xq.order, o...)
	return xq
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

// Clone returns a duplicate of the XunjiQuery builder, including all associated steps. It can be
// used to prepare common query builders and use them differently after the clone is made.
func (xq *XunjiQuery) Clone() *XunjiQuery {
	if xq == nil {
		return nil
	}
	return &XunjiQuery{
		config:     xq.config,
		ctx:        xq.ctx.Clone(),
		order:      append([]xunji.OrderOption{}, xq.order...),
		inters:     append([]Interceptor{}, xq.inters...),
		predicates: append([]predicate.Xunji{}, xq.predicates...),
		// clone intermediate query.
		sql:  xq.sql.Clone(),
		path: xq.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.Xunji.Query().
//		GroupBy(xunji.FieldCreatedAt).
//		Aggregate(ent.Count()).
//		Scan(ctx, &v)
func (xq *XunjiQuery) GroupBy(field string, fields ...string) *XunjiGroupBy {
	xq.ctx.Fields = append([]string{field}, fields...)
	grbuild := &XunjiGroupBy{build: xq}
	grbuild.flds = &xq.ctx.Fields
	grbuild.label = xunji.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.Xunji.Query().
//		Select(xunji.FieldCreatedAt).
//		Scan(ctx, &v)
func (xq *XunjiQuery) Select(fields ...string) *XunjiSelect {
	xq.ctx.Fields = append(xq.ctx.Fields, fields...)
	sbuild := &XunjiSelect{XunjiQuery: xq}
	sbuild.label = xunji.Label
	sbuild.flds, sbuild.scan = &xq.ctx.Fields, sbuild.Scan
	return sbuild
}

// Aggregate returns a XunjiSelect configured with the given aggregations.
func (xq *XunjiQuery) Aggregate(fns ...AggregateFunc) *XunjiSelect {
	return xq.Select().Aggregate(fns...)
}

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

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

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

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

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

// XunjiGroupBy is the group-by builder for Xunji entities.
type XunjiGroupBy struct {
	selector
	build *XunjiQuery
}

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

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

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

// XunjiSelect is the builder for selecting fields of Xunji entities.
type XunjiSelect struct {
	*XunjiQuery
	selector
}

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

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

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