// Code generated by ent, DO NOT EDIT.

package ent

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

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

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

// Where adds a new predicate for the WxCardQuery builder.
func (wcq *WxCardQuery) Where(ps ...predicate.WxCard) *WxCardQuery {
	wcq.predicates = append(wcq.predicates, ps...)
	return wcq
}

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

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

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

// Order specifies how the records should be ordered.
func (wcq *WxCardQuery) Order(o ...wxcard.OrderOption) *WxCardQuery {
	wcq.order = append(wcq.order, o...)
	return wcq
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

// Aggregate returns a WxCardSelect configured with the given aggregations.
func (wcq *WxCardQuery) Aggregate(fns ...AggregateFunc) *WxCardSelect {
	return wcq.Select().Aggregate(fns...)
}

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

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

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

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

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

// WxCardGroupBy is the group-by builder for WxCard entities.
type WxCardGroupBy struct {
	selector
	build *WxCardQuery
}

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

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

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

// WxCardSelect is the builder for selecting fields of WxCard entities.
type WxCardSelect struct {
	*WxCardQuery
	selector
}

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

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

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