// Code generated by ent, DO NOT EDIT.

package ent

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

// WhatsappChannelGroupBy is the group-by builder for WhatsappChannel entities.
type WhatsappChannelGroupBy struct {
	selector
	build *WhatsappChannelQuery
}

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

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

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

// WhatsappChannelSelect is the builder for selecting fields of WhatsappChannel entities.
type WhatsappChannelSelect struct {
	*WhatsappChannelQuery
	selector
}

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

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

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