// Code generated by ent, DO NOT EDIT.

package ent

import (
	"context"
	"fmt"
	"math"

	"entgo.io/ent"
	"entgo.io/ent/dialect/sql"
	"entgo.io/ent/dialect/sql/sqlgraph"
	"entgo.io/ent/schema/field"
	"github.com/buildbarn/bb-portal/ent/gen/ent/predicate"
	"github.com/buildbarn/bb-portal/ent/gen/ent/timingbreakdown"
	"github.com/buildbarn/bb-portal/ent/gen/ent/timingchild"
)

// TimingChildQuery is the builder for querying TimingChild entities.
type TimingChildQuery struct {
	config
	ctx                 *QueryContext
	order               []timingchild.OrderOption
	inters              []Interceptor
	predicates          []predicate.TimingChild
	withTimingBreakdown *TimingBreakdownQuery
	withFKs             bool
	modifiers           []func(*sql.Selector)
	loadTotal           []func(context.Context, []*TimingChild) error
	// intermediate query (i.e. traversal path).
	sql  *sql.Selector
	path func(context.Context) (*sql.Selector, error)
}

// Where adds a new predicate for the TimingChildQuery builder.
func (tcq *TimingChildQuery) Where(ps ...predicate.TimingChild) *TimingChildQuery {
	tcq.predicates = append(tcq.predicates, ps...)
	return tcq
}

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

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

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

// Order specifies how the records should be ordered.
func (tcq *TimingChildQuery) Order(o ...timingchild.OrderOption) *TimingChildQuery {
	tcq.order = append(tcq.order, o...)
	return tcq
}

// QueryTimingBreakdown chains the current query on the "timing_breakdown" edge.
func (tcq *TimingChildQuery) QueryTimingBreakdown() *TimingBreakdownQuery {
	query := (&TimingBreakdownClient{config: tcq.config}).Query()
	query.path = func(ctx context.Context) (fromU *sql.Selector, err error) {
		if err := tcq.prepareQuery(ctx); err != nil {
			return nil, err
		}
		selector := tcq.sqlQuery(ctx)
		if err := selector.Err(); err != nil {
			return nil, err
		}
		step := sqlgraph.NewStep(
			sqlgraph.From(timingchild.Table, timingchild.FieldID, selector),
			sqlgraph.To(timingbreakdown.Table, timingbreakdown.FieldID),
			sqlgraph.Edge(sqlgraph.M2O, true, timingchild.TimingBreakdownTable, timingchild.TimingBreakdownColumn),
		)
		fromU = sqlgraph.SetNeighbors(tcq.driver.Dialect(), step)
		return fromU, nil
	}
	return query
}

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

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

// FirstID returns the first TimingChild ID from the query.
// Returns a *NotFoundError when no TimingChild ID was found.
func (tcq *TimingChildQuery) FirstID(ctx context.Context) (id int, err error) {
	var ids []int
	if ids, err = tcq.Limit(1).IDs(setContextOp(ctx, tcq.ctx, ent.OpQueryFirstID)); err != nil {
		return
	}
	if len(ids) == 0 {
		err = &NotFoundError{timingchild.Label}
		return
	}
	return ids[0], nil
}

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

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

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

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

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

// All executes the query and returns a list of TimingChilds.
func (tcq *TimingChildQuery) All(ctx context.Context) ([]*TimingChild, error) {
	ctx = setContextOp(ctx, tcq.ctx, ent.OpQueryAll)
	if err := tcq.prepareQuery(ctx); err != nil {
		return nil, err
	}
	qr := querierAll[[]*TimingChild, *TimingChildQuery]()
	return withInterceptors[[]*TimingChild](ctx, tcq, qr, tcq.inters)
}

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

// IDs executes the query and returns a list of TimingChild IDs.
func (tcq *TimingChildQuery) IDs(ctx context.Context) (ids []int, err error) {
	if tcq.ctx.Unique == nil && tcq.path != nil {
		tcq.Unique(true)
	}
	ctx = setContextOp(ctx, tcq.ctx, ent.OpQueryIDs)
	if err = tcq.Select(timingchild.FieldID).Scan(ctx, &ids); err != nil {
		return nil, err
	}
	return ids, nil
}

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

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

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

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

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

// WithTimingBreakdown tells the query-builder to eager-load the nodes that are connected to
// the "timing_breakdown" edge. The optional arguments are used to configure the query builder of the edge.
func (tcq *TimingChildQuery) WithTimingBreakdown(opts ...func(*TimingBreakdownQuery)) *TimingChildQuery {
	query := (&TimingBreakdownClient{config: tcq.config}).Query()
	for _, opt := range opts {
		opt(query)
	}
	tcq.withTimingBreakdown = query
	return tcq
}

// 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 {
//		Name string `json:"name,omitempty"`
//		Count int `json:"count,omitempty"`
//	}
//
//	client.TimingChild.Query().
//		GroupBy(timingchild.FieldName).
//		Aggregate(ent.Count()).
//		Scan(ctx, &v)
func (tcq *TimingChildQuery) GroupBy(field string, fields ...string) *TimingChildGroupBy {
	tcq.ctx.Fields = append([]string{field}, fields...)
	grbuild := &TimingChildGroupBy{build: tcq}
	grbuild.flds = &tcq.ctx.Fields
	grbuild.label = timingchild.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 {
//		Name string `json:"name,omitempty"`
//	}
//
//	client.TimingChild.Query().
//		Select(timingchild.FieldName).
//		Scan(ctx, &v)
func (tcq *TimingChildQuery) Select(fields ...string) *TimingChildSelect {
	tcq.ctx.Fields = append(tcq.ctx.Fields, fields...)
	sbuild := &TimingChildSelect{TimingChildQuery: tcq}
	sbuild.label = timingchild.Label
	sbuild.flds, sbuild.scan = &tcq.ctx.Fields, sbuild.Scan
	return sbuild
}

// Aggregate returns a TimingChildSelect configured with the given aggregations.
func (tcq *TimingChildQuery) Aggregate(fns ...AggregateFunc) *TimingChildSelect {
	return tcq.Select().Aggregate(fns...)
}

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

func (tcq *TimingChildQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*TimingChild, error) {
	var (
		nodes       = []*TimingChild{}
		withFKs     = tcq.withFKs
		_spec       = tcq.querySpec()
		loadedTypes = [1]bool{
			tcq.withTimingBreakdown != nil,
		}
	)
	if tcq.withTimingBreakdown != nil {
		withFKs = true
	}
	if withFKs {
		_spec.Node.Columns = append(_spec.Node.Columns, timingchild.ForeignKeys...)
	}
	_spec.ScanValues = func(columns []string) ([]any, error) {
		return (*TimingChild).scanValues(nil, columns)
	}
	_spec.Assign = func(columns []string, values []any) error {
		node := &TimingChild{config: tcq.config}
		nodes = append(nodes, node)
		node.Edges.loadedTypes = loadedTypes
		return node.assignValues(columns, values)
	}
	if len(tcq.modifiers) > 0 {
		_spec.Modifiers = tcq.modifiers
	}
	for i := range hooks {
		hooks[i](ctx, _spec)
	}
	if err := sqlgraph.QueryNodes(ctx, tcq.driver, _spec); err != nil {
		return nil, err
	}
	if len(nodes) == 0 {
		return nodes, nil
	}
	if query := tcq.withTimingBreakdown; query != nil {
		if err := tcq.loadTimingBreakdown(ctx, query, nodes, nil,
			func(n *TimingChild, e *TimingBreakdown) { n.Edges.TimingBreakdown = e }); err != nil {
			return nil, err
		}
	}
	for i := range tcq.loadTotal {
		if err := tcq.loadTotal[i](ctx, nodes); err != nil {
			return nil, err
		}
	}
	return nodes, nil
}

func (tcq *TimingChildQuery) loadTimingBreakdown(ctx context.Context, query *TimingBreakdownQuery, nodes []*TimingChild, init func(*TimingChild), assign func(*TimingChild, *TimingBreakdown)) error {
	ids := make([]int, 0, len(nodes))
	nodeids := make(map[int][]*TimingChild)
	for i := range nodes {
		if nodes[i].timing_breakdown_child == nil {
			continue
		}
		fk := *nodes[i].timing_breakdown_child
		if _, ok := nodeids[fk]; !ok {
			ids = append(ids, fk)
		}
		nodeids[fk] = append(nodeids[fk], nodes[i])
	}
	if len(ids) == 0 {
		return nil
	}
	query.Where(timingbreakdown.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 "timing_breakdown_child" returned %v`, n.ID)
		}
		for i := range nodes {
			assign(nodes[i], n)
		}
	}
	return nil
}

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

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

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

// TimingChildGroupBy is the group-by builder for TimingChild entities.
type TimingChildGroupBy struct {
	selector
	build *TimingChildQuery
}

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

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

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

// TimingChildSelect is the builder for selecting fields of TimingChild entities.
type TimingChildSelect struct {
	*TimingChildQuery
	selector
}

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

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

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