// 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/cumulativemetrics"
	"github.com/buildbarn/bb-portal/ent/gen/ent/metrics"
	"github.com/buildbarn/bb-portal/ent/gen/ent/predicate"
)

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

// Where adds a new predicate for the CumulativeMetricsQuery builder.
func (cmq *CumulativeMetricsQuery) Where(ps ...predicate.CumulativeMetrics) *CumulativeMetricsQuery {
	cmq.predicates = append(cmq.predicates, ps...)
	return cmq
}

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

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

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

// Order specifies how the records should be ordered.
func (cmq *CumulativeMetricsQuery) Order(o ...cumulativemetrics.OrderOption) *CumulativeMetricsQuery {
	cmq.order = append(cmq.order, o...)
	return cmq
}

// QueryMetrics chains the current query on the "metrics" edge.
func (cmq *CumulativeMetricsQuery) QueryMetrics() *MetricsQuery {
	query := (&MetricsClient{config: cmq.config}).Query()
	query.path = func(ctx context.Context) (fromU *sql.Selector, err error) {
		if err := cmq.prepareQuery(ctx); err != nil {
			return nil, err
		}
		selector := cmq.sqlQuery(ctx)
		if err := selector.Err(); err != nil {
			return nil, err
		}
		step := sqlgraph.NewStep(
			sqlgraph.From(cumulativemetrics.Table, cumulativemetrics.FieldID, selector),
			sqlgraph.To(metrics.Table, metrics.FieldID),
			sqlgraph.Edge(sqlgraph.O2O, true, cumulativemetrics.MetricsTable, cumulativemetrics.MetricsColumn),
		)
		fromU = sqlgraph.SetNeighbors(cmq.driver.Dialect(), step)
		return fromU, nil
	}
	return query
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

// WithMetrics tells the query-builder to eager-load the nodes that are connected to
// the "metrics" edge. The optional arguments are used to configure the query builder of the edge.
func (cmq *CumulativeMetricsQuery) WithMetrics(opts ...func(*MetricsQuery)) *CumulativeMetricsQuery {
	query := (&MetricsClient{config: cmq.config}).Query()
	for _, opt := range opts {
		opt(query)
	}
	cmq.withMetrics = query
	return cmq
}

// 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 {
//		NumAnalyses int32 `json:"num_analyses,omitempty"`
//		Count int `json:"count,omitempty"`
//	}
//
//	client.CumulativeMetrics.Query().
//		GroupBy(cumulativemetrics.FieldNumAnalyses).
//		Aggregate(ent.Count()).
//		Scan(ctx, &v)
func (cmq *CumulativeMetricsQuery) GroupBy(field string, fields ...string) *CumulativeMetricsGroupBy {
	cmq.ctx.Fields = append([]string{field}, fields...)
	grbuild := &CumulativeMetricsGroupBy{build: cmq}
	grbuild.flds = &cmq.ctx.Fields
	grbuild.label = cumulativemetrics.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 {
//		NumAnalyses int32 `json:"num_analyses,omitempty"`
//	}
//
//	client.CumulativeMetrics.Query().
//		Select(cumulativemetrics.FieldNumAnalyses).
//		Scan(ctx, &v)
func (cmq *CumulativeMetricsQuery) Select(fields ...string) *CumulativeMetricsSelect {
	cmq.ctx.Fields = append(cmq.ctx.Fields, fields...)
	sbuild := &CumulativeMetricsSelect{CumulativeMetricsQuery: cmq}
	sbuild.label = cumulativemetrics.Label
	sbuild.flds, sbuild.scan = &cmq.ctx.Fields, sbuild.Scan
	return sbuild
}

// Aggregate returns a CumulativeMetricsSelect configured with the given aggregations.
func (cmq *CumulativeMetricsQuery) Aggregate(fns ...AggregateFunc) *CumulativeMetricsSelect {
	return cmq.Select().Aggregate(fns...)
}

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

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

func (cmq *CumulativeMetricsQuery) loadMetrics(ctx context.Context, query *MetricsQuery, nodes []*CumulativeMetrics, init func(*CumulativeMetrics), assign func(*CumulativeMetrics, *Metrics)) error {
	ids := make([]int, 0, len(nodes))
	nodeids := make(map[int][]*CumulativeMetrics)
	for i := range nodes {
		if nodes[i].metrics_cumulative_metrics == nil {
			continue
		}
		fk := *nodes[i].metrics_cumulative_metrics
		if _, ok := nodeids[fk]; !ok {
			ids = append(ids, fk)
		}
		nodeids[fk] = append(nodeids[fk], nodes[i])
	}
	if len(ids) == 0 {
		return nil
	}
	query.Where(metrics.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 "metrics_cumulative_metrics" returned %v`, n.ID)
		}
		for i := range nodes {
			assign(nodes[i], n)
		}
	}
	return nil
}

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

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

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

// CumulativeMetricsGroupBy is the group-by builder for CumulativeMetrics entities.
type CumulativeMetricsGroupBy struct {
	selector
	build *CumulativeMetricsQuery
}

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

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

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

// CumulativeMetricsSelect is the builder for selecting fields of CumulativeMetrics entities.
type CumulativeMetricsSelect struct {
	*CumulativeMetricsQuery
	selector
}

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

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

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