// Code generated by ent, DO NOT EDIT.

package ent

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

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

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

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

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

// Offset to start from.
func (wcq *WpChatroomQuery) Offset(offset int) *WpChatroomQuery {
	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 *WpChatroomQuery) Unique(unique bool) *WpChatroomQuery {
	wcq.ctx.Unique = &unique
	return wcq
}

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

// First returns the first WpChatroom entity from the query.
// Returns a *NotFoundError when no WpChatroom was found.
func (wcq *WpChatroomQuery) First(ctx context.Context) (*WpChatroom, 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{wpchatroom.Label}
	}
	return nodes[0], nil
}

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

// FirstID returns the first WpChatroom ID from the query.
// Returns a *NotFoundError when no WpChatroom ID was found.
func (wcq *WpChatroomQuery) 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{wpchatroom.Label}
		return
	}
	return ids[0], nil
}

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

// Only returns a single WpChatroom entity found by the query, ensuring it only returns one.
// Returns a *NotSingularError when more than one WpChatroom entity is found.
// Returns a *NotFoundError when no WpChatroom entities are found.
func (wcq *WpChatroomQuery) Only(ctx context.Context) (*WpChatroom, 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{wpchatroom.Label}
	default:
		return nil, &NotSingularError{wpchatroom.Label}
	}
}

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

// OnlyID is like Only, but returns the only WpChatroom ID in the query.
// Returns a *NotSingularError when more than one WpChatroom ID is found.
// Returns a *NotFoundError when no entities are found.
func (wcq *WpChatroomQuery) 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{wpchatroom.Label}
	default:
		err = &NotSingularError{wpchatroom.Label}
	}
	return
}

// OnlyIDX is like OnlyID, but panics if an error occurs.
func (wcq *WpChatroomQuery) 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 WpChatrooms.
func (wcq *WpChatroomQuery) All(ctx context.Context) ([]*WpChatroom, error) {
	ctx = setContextOp(ctx, wcq.ctx, "All")
	if err := wcq.prepareQuery(ctx); err != nil {
		return nil, err
	}
	qr := querierAll[[]*WpChatroom, *WpChatroomQuery]()
	return withInterceptors[[]*WpChatroom](ctx, wcq, qr, wcq.inters)
}

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

// IDs executes the query and returns a list of WpChatroom IDs.
func (wcq *WpChatroomQuery) 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(wpchatroom.FieldID).Scan(ctx, &ids); err != nil {
		return nil, err
	}
	return ids, nil
}

// IDsX is like IDs, but panics if an error occurs.
func (wcq *WpChatroomQuery) 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 *WpChatroomQuery) 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[*WpChatroomQuery](), wcq.inters)
}

// CountX is like Count, but panics if an error occurs.
func (wcq *WpChatroomQuery) 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 *WpChatroomQuery) 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 *WpChatroomQuery) ExistX(ctx context.Context) bool {
	exist, err := wcq.Exist(ctx)
	if err != nil {
		panic(err)
	}
	return exist
}

// Clone returns a duplicate of the WpChatroomQuery 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 *WpChatroomQuery) Clone() *WpChatroomQuery {
	if wcq == nil {
		return nil
	}
	return &WpChatroomQuery{
		config:     wcq.config,
		ctx:        wcq.ctx.Clone(),
		order:      append([]wpchatroom.OrderOption{}, wcq.order...),
		inters:     append([]Interceptor{}, wcq.inters...),
		predicates: append([]predicate.WpChatroom{}, 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.WpChatroom.Query().
//		GroupBy(wpchatroom.FieldCreatedAt).
//		Aggregate(ent.Count()).
//		Scan(ctx, &v)
func (wcq *WpChatroomQuery) GroupBy(field string, fields ...string) *WpChatroomGroupBy {
	wcq.ctx.Fields = append([]string{field}, fields...)
	grbuild := &WpChatroomGroupBy{build: wcq}
	grbuild.flds = &wcq.ctx.Fields
	grbuild.label = wpchatroom.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.WpChatroom.Query().
//		Select(wpchatroom.FieldCreatedAt).
//		Scan(ctx, &v)
func (wcq *WpChatroomQuery) Select(fields ...string) *WpChatroomSelect {
	wcq.ctx.Fields = append(wcq.ctx.Fields, fields...)
	sbuild := &WpChatroomSelect{WpChatroomQuery: wcq}
	sbuild.label = wpchatroom.Label
	sbuild.flds, sbuild.scan = &wcq.ctx.Fields, sbuild.Scan
	return sbuild
}

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

func (wcq *WpChatroomQuery) 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 !wpchatroom.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 *WpChatroomQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*WpChatroom, error) {
	var (
		nodes = []*WpChatroom{}
		_spec = wcq.querySpec()
	)
	_spec.ScanValues = func(columns []string) ([]any, error) {
		return (*WpChatroom).scanValues(nil, columns)
	}
	_spec.Assign = func(columns []string, values []any) error {
		node := &WpChatroom{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 *WpChatroomQuery) 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 *WpChatroomQuery) querySpec() *sqlgraph.QuerySpec {
	_spec := sqlgraph.NewQuerySpec(wpchatroom.Table, wpchatroom.Columns, sqlgraph.NewFieldSpec(wpchatroom.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, wpchatroom.FieldID)
		for i := range fields {
			if fields[i] != wpchatroom.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 *WpChatroomQuery) sqlQuery(ctx context.Context) *sql.Selector {
	builder := sql.Dialect(wcq.driver.Dialect())
	t1 := builder.Table(wpchatroom.Table)
	columns := wcq.ctx.Fields
	if len(columns) == 0 {
		columns = wpchatroom.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
}

// WpChatroomGroupBy is the group-by builder for WpChatroom entities.
type WpChatroomGroupBy struct {
	selector
	build *WpChatroomQuery
}

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

// Scan applies the selector query and scans the result into the given value.
func (wcgb *WpChatroomGroupBy) 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[*WpChatroomQuery, *WpChatroomGroupBy](ctx, wcgb.build, wcgb, wcgb.build.inters, v)
}

func (wcgb *WpChatroomGroupBy) sqlScan(ctx context.Context, root *WpChatroomQuery, 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)
}

// WpChatroomSelect is the builder for selecting fields of WpChatroom entities.
type WpChatroomSelect struct {
	*WpChatroomQuery
	selector
}

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

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

func (wcs *WpChatroomSelect) sqlScan(ctx context.Context, root *WpChatroomQuery, 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)
}
