// Code generated by ent, DO NOT EDIT.

package ent

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

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

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

// Where adds a new predicate for the CreditUsageQuery builder.
func (cuq *CreditUsageQuery) Where(ps ...predicate.CreditUsage) *CreditUsageQuery {
	cuq.predicates = append(cuq.predicates, ps...)
	return cuq
}

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

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

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

// Order specifies how the records should be ordered.
func (cuq *CreditUsageQuery) Order(o ...creditusage.OrderOption) *CreditUsageQuery {
	cuq.order = append(cuq.order, o...)
	return cuq
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

// Aggregate returns a CreditUsageSelect configured with the given aggregations.
func (cuq *CreditUsageQuery) Aggregate(fns ...AggregateFunc) *CreditUsageSelect {
	return cuq.Select().Aggregate(fns...)
}

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

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

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

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

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

// CreditUsageGroupBy is the group-by builder for CreditUsage entities.
type CreditUsageGroupBy struct {
	selector
	build *CreditUsageQuery
}

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

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

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

// CreditUsageSelect is the builder for selecting fields of CreditUsage entities.
type CreditUsageSelect struct {
	*CreditUsageQuery
	selector
}

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

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

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