// Code generated by ent, DO NOT EDIT.

package ent

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

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

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

// Where adds a new predicate for the LabelRelationshipQuery builder.
func (lrq *LabelRelationshipQuery) Where(ps ...predicate.LabelRelationship) *LabelRelationshipQuery {
	lrq.predicates = append(lrq.predicates, ps...)
	return lrq
}

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

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

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

// Order specifies how the records should be ordered.
func (lrq *LabelRelationshipQuery) Order(o ...labelrelationship.OrderOption) *LabelRelationshipQuery {
	lrq.order = append(lrq.order, o...)
	return lrq
}

// QueryContacts chains the current query on the "contacts" edge.
func (lrq *LabelRelationshipQuery) QueryContacts() *ContactQuery {
	query := (&ContactClient{config: lrq.config}).Query()
	query.path = func(ctx context.Context) (fromU *sql.Selector, err error) {
		if err := lrq.prepareQuery(ctx); err != nil {
			return nil, err
		}
		selector := lrq.sqlQuery(ctx)
		if err := selector.Err(); err != nil {
			return nil, err
		}
		step := sqlgraph.NewStep(
			sqlgraph.From(labelrelationship.Table, labelrelationship.FieldID, selector),
			sqlgraph.To(contact.Table, contact.FieldID),
			sqlgraph.Edge(sqlgraph.M2O, true, labelrelationship.ContactsTable, labelrelationship.ContactsColumn),
		)
		fromU = sqlgraph.SetNeighbors(lrq.driver.Dialect(), step)
		return fromU, nil
	}
	return query
}

// QueryLabels chains the current query on the "labels" edge.
func (lrq *LabelRelationshipQuery) QueryLabels() *LabelQuery {
	query := (&LabelClient{config: lrq.config}).Query()
	query.path = func(ctx context.Context) (fromU *sql.Selector, err error) {
		if err := lrq.prepareQuery(ctx); err != nil {
			return nil, err
		}
		selector := lrq.sqlQuery(ctx)
		if err := selector.Err(); err != nil {
			return nil, err
		}
		step := sqlgraph.NewStep(
			sqlgraph.From(labelrelationship.Table, labelrelationship.FieldID, selector),
			sqlgraph.To(label.Table, label.FieldID),
			sqlgraph.Edge(sqlgraph.M2O, true, labelrelationship.LabelsTable, labelrelationship.LabelsColumn),
		)
		fromU = sqlgraph.SetNeighbors(lrq.driver.Dialect(), step)
		return fromU, nil
	}
	return query
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

// WithLabels tells the query-builder to eager-load the nodes that are connected to
// the "labels" edge. The optional arguments are used to configure the query builder of the edge.
func (lrq *LabelRelationshipQuery) WithLabels(opts ...func(*LabelQuery)) *LabelRelationshipQuery {
	query := (&LabelClient{config: lrq.config}).Query()
	for _, opt := range opts {
		opt(query)
	}
	lrq.withLabels = query
	return lrq
}

// 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.LabelRelationship.Query().
//		GroupBy(labelrelationship.FieldCreatedAt).
//		Aggregate(ent.Count()).
//		Scan(ctx, &v)
func (lrq *LabelRelationshipQuery) GroupBy(field string, fields ...string) *LabelRelationshipGroupBy {
	lrq.ctx.Fields = append([]string{field}, fields...)
	grbuild := &LabelRelationshipGroupBy{build: lrq}
	grbuild.flds = &lrq.ctx.Fields
	grbuild.label = labelrelationship.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.LabelRelationship.Query().
//		Select(labelrelationship.FieldCreatedAt).
//		Scan(ctx, &v)
func (lrq *LabelRelationshipQuery) Select(fields ...string) *LabelRelationshipSelect {
	lrq.ctx.Fields = append(lrq.ctx.Fields, fields...)
	sbuild := &LabelRelationshipSelect{LabelRelationshipQuery: lrq}
	sbuild.label = labelrelationship.Label
	sbuild.flds, sbuild.scan = &lrq.ctx.Fields, sbuild.Scan
	return sbuild
}

// Aggregate returns a LabelRelationshipSelect configured with the given aggregations.
func (lrq *LabelRelationshipQuery) Aggregate(fns ...AggregateFunc) *LabelRelationshipSelect {
	return lrq.Select().Aggregate(fns...)
}

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

func (lrq *LabelRelationshipQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*LabelRelationship, error) {
	var (
		nodes       = []*LabelRelationship{}
		_spec       = lrq.querySpec()
		loadedTypes = [2]bool{
			lrq.withContacts != nil,
			lrq.withLabels != nil,
		}
	)
	_spec.ScanValues = func(columns []string) ([]any, error) {
		return (*LabelRelationship).scanValues(nil, columns)
	}
	_spec.Assign = func(columns []string, values []any) error {
		node := &LabelRelationship{config: lrq.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, lrq.driver, _spec); err != nil {
		return nil, err
	}
	if len(nodes) == 0 {
		return nodes, nil
	}
	if query := lrq.withContacts; query != nil {
		if err := lrq.loadContacts(ctx, query, nodes, nil,
			func(n *LabelRelationship, e *Contact) { n.Edges.Contacts = e }); err != nil {
			return nil, err
		}
	}
	if query := lrq.withLabels; query != nil {
		if err := lrq.loadLabels(ctx, query, nodes, nil,
			func(n *LabelRelationship, e *Label) { n.Edges.Labels = e }); err != nil {
			return nil, err
		}
	}
	return nodes, nil
}

func (lrq *LabelRelationshipQuery) loadContacts(ctx context.Context, query *ContactQuery, nodes []*LabelRelationship, init func(*LabelRelationship), assign func(*LabelRelationship, *Contact)) error {
	ids := make([]uint64, 0, len(nodes))
	nodeids := make(map[uint64][]*LabelRelationship)
	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 (lrq *LabelRelationshipQuery) loadLabels(ctx context.Context, query *LabelQuery, nodes []*LabelRelationship, init func(*LabelRelationship), assign func(*LabelRelationship, *Label)) error {
	ids := make([]uint64, 0, len(nodes))
	nodeids := make(map[uint64][]*LabelRelationship)
	for i := range nodes {
		fk := nodes[i].LabelID
		if _, ok := nodeids[fk]; !ok {
			ids = append(ids, fk)
		}
		nodeids[fk] = append(nodeids[fk], nodes[i])
	}
	if len(ids) == 0 {
		return nil
	}
	query.Where(label.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 "label_id" returned %v`, n.ID)
		}
		for i := range nodes {
			assign(nodes[i], n)
		}
	}
	return nil
}

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

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

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

// LabelRelationshipGroupBy is the group-by builder for LabelRelationship entities.
type LabelRelationshipGroupBy struct {
	selector
	build *LabelRelationshipQuery
}

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

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

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

// LabelRelationshipSelect is the builder for selecting fields of LabelRelationship entities.
type LabelRelationshipSelect struct {
	*LabelRelationshipQuery
	selector
}

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

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

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