// Code generated by ent, DO NOT EDIT.

package ent

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

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

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

// Where adds a new predicate for the ContactFieldQuery builder.
func (cfq *ContactFieldQuery) Where(ps ...predicate.ContactField) *ContactFieldQuery {
	cfq.predicates = append(cfq.predicates, ps...)
	return cfq
}

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

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

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

// Order specifies how the records should be ordered.
func (cfq *ContactFieldQuery) Order(o ...contactfield.OrderOption) *ContactFieldQuery {
	cfq.order = append(cfq.order, o...)
	return cfq
}

// QueryFieldContact chains the current query on the "field_contact" edge.
func (cfq *ContactFieldQuery) QueryFieldContact() *ContactQuery {
	query := (&ContactClient{config: cfq.config}).Query()
	query.path = func(ctx context.Context) (fromU *sql.Selector, err error) {
		if err := cfq.prepareQuery(ctx); err != nil {
			return nil, err
		}
		selector := cfq.sqlQuery(ctx)
		if err := selector.Err(); err != nil {
			return nil, err
		}
		step := sqlgraph.NewStep(
			sqlgraph.From(contactfield.Table, contactfield.FieldID, selector),
			sqlgraph.To(contact.Table, contact.FieldID),
			sqlgraph.Edge(sqlgraph.M2O, true, contactfield.FieldContactTable, contactfield.FieldContactColumn),
		)
		fromU = sqlgraph.SetNeighbors(cfq.driver.Dialect(), step)
		return fromU, nil
	}
	return query
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

// Clone returns a duplicate of the ContactFieldQuery builder, including all associated steps. It can be
// used to prepare common query builders and use them differently after the clone is made.
func (cfq *ContactFieldQuery) Clone() *ContactFieldQuery {
	if cfq == nil {
		return nil
	}
	return &ContactFieldQuery{
		config:           cfq.config,
		ctx:              cfq.ctx.Clone(),
		order:            append([]contactfield.OrderOption{}, cfq.order...),
		inters:           append([]Interceptor{}, cfq.inters...),
		predicates:       append([]predicate.ContactField{}, cfq.predicates...),
		withFieldContact: cfq.withFieldContact.Clone(),
		// clone intermediate query.
		sql:  cfq.sql.Clone(),
		path: cfq.path,
	}
}

// WithFieldContact tells the query-builder to eager-load the nodes that are connected to
// the "field_contact" edge. The optional arguments are used to configure the query builder of the edge.
func (cfq *ContactFieldQuery) WithFieldContact(opts ...func(*ContactQuery)) *ContactFieldQuery {
	query := (&ContactClient{config: cfq.config}).Query()
	for _, opt := range opts {
		opt(query)
	}
	cfq.withFieldContact = query
	return cfq
}

// 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.ContactField.Query().
//		GroupBy(contactfield.FieldCreatedAt).
//		Aggregate(ent.Count()).
//		Scan(ctx, &v)
func (cfq *ContactFieldQuery) GroupBy(field string, fields ...string) *ContactFieldGroupBy {
	cfq.ctx.Fields = append([]string{field}, fields...)
	grbuild := &ContactFieldGroupBy{build: cfq}
	grbuild.flds = &cfq.ctx.Fields
	grbuild.label = contactfield.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.ContactField.Query().
//		Select(contactfield.FieldCreatedAt).
//		Scan(ctx, &v)
func (cfq *ContactFieldQuery) Select(fields ...string) *ContactFieldSelect {
	cfq.ctx.Fields = append(cfq.ctx.Fields, fields...)
	sbuild := &ContactFieldSelect{ContactFieldQuery: cfq}
	sbuild.label = contactfield.Label
	sbuild.flds, sbuild.scan = &cfq.ctx.Fields, sbuild.Scan
	return sbuild
}

// Aggregate returns a ContactFieldSelect configured with the given aggregations.
func (cfq *ContactFieldQuery) Aggregate(fns ...AggregateFunc) *ContactFieldSelect {
	return cfq.Select().Aggregate(fns...)
}

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

func (cfq *ContactFieldQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*ContactField, error) {
	var (
		nodes       = []*ContactField{}
		_spec       = cfq.querySpec()
		loadedTypes = [1]bool{
			cfq.withFieldContact != nil,
		}
	)
	_spec.ScanValues = func(columns []string) ([]any, error) {
		return (*ContactField).scanValues(nil, columns)
	}
	_spec.Assign = func(columns []string, values []any) error {
		node := &ContactField{config: cfq.config}
		nodes = append(nodes, node)
		node.Edges.loadedTypes = loadedTypes
		return node.assignValues(columns, values)
	}
	for i := range hooks {
		hooks[i](ctx, _spec)
	}
	if err := sqlgraph.QueryNodes(ctx, cfq.driver, _spec); err != nil {
		return nil, err
	}
	if len(nodes) == 0 {
		return nodes, nil
	}
	if query := cfq.withFieldContact; query != nil {
		if err := cfq.loadFieldContact(ctx, query, nodes, nil,
			func(n *ContactField, e *Contact) { n.Edges.FieldContact = e }); err != nil {
			return nil, err
		}
	}
	return nodes, nil
}

func (cfq *ContactFieldQuery) loadFieldContact(ctx context.Context, query *ContactQuery, nodes []*ContactField, init func(*ContactField), assign func(*ContactField, *Contact)) error {
	ids := make([]uint64, 0, len(nodes))
	nodeids := make(map[uint64][]*ContactField)
	for i := range nodes {
		fk := nodes[i].ContactID
		if _, ok := nodeids[fk]; !ok {
			ids = append(ids, fk)
		}
		nodeids[fk] = append(nodeids[fk], nodes[i])
	}
	if len(ids) == 0 {
		return nil
	}
	query.Where(contact.IDIn(ids...))
	neighbors, err := query.All(ctx)
	if err != nil {
		return err
	}
	for _, n := range neighbors {
		nodes, ok := nodeids[n.ID]
		if !ok {
			return fmt.Errorf(`unexpected foreign-key "contact_id" returned %v`, n.ID)
		}
		for i := range nodes {
			assign(nodes[i], n)
		}
	}
	return nil
}

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

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

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

// ContactFieldGroupBy is the group-by builder for ContactField entities.
type ContactFieldGroupBy struct {
	selector
	build *ContactFieldQuery
}

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

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

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

// ContactFieldSelect is the builder for selecting fields of ContactField entities.
type ContactFieldSelect struct {
	*ContactFieldQuery
	selector
}

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

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

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