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

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

// Where adds a new predicate for the PackageLoadMetricsQuery builder.
func (plmq *PackageLoadMetricsQuery) Where(ps ...predicate.PackageLoadMetrics) *PackageLoadMetricsQuery {
	plmq.predicates = append(plmq.predicates, ps...)
	return plmq
}

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

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

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

// Order specifies how the records should be ordered.
func (plmq *PackageLoadMetricsQuery) Order(o ...packageloadmetrics.OrderOption) *PackageLoadMetricsQuery {
	plmq.order = append(plmq.order, o...)
	return plmq
}

// QueryPackageMetrics chains the current query on the "package_metrics" edge.
func (plmq *PackageLoadMetricsQuery) QueryPackageMetrics() *PackageMetricsQuery {
	query := (&PackageMetricsClient{config: plmq.config}).Query()
	query.path = func(ctx context.Context) (fromU *sql.Selector, err error) {
		if err := plmq.prepareQuery(ctx); err != nil {
			return nil, err
		}
		selector := plmq.sqlQuery(ctx)
		if err := selector.Err(); err != nil {
			return nil, err
		}
		step := sqlgraph.NewStep(
			sqlgraph.From(packageloadmetrics.Table, packageloadmetrics.FieldID, selector),
			sqlgraph.To(packagemetrics.Table, packagemetrics.FieldID),
			sqlgraph.Edge(sqlgraph.M2O, true, packageloadmetrics.PackageMetricsTable, packageloadmetrics.PackageMetricsColumn),
		)
		fromU = sqlgraph.SetNeighbors(plmq.driver.Dialect(), step)
		return fromU, nil
	}
	return query
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

// WithPackageMetrics tells the query-builder to eager-load the nodes that are connected to
// the "package_metrics" edge. The optional arguments are used to configure the query builder of the edge.
func (plmq *PackageLoadMetricsQuery) WithPackageMetrics(opts ...func(*PackageMetricsQuery)) *PackageLoadMetricsQuery {
	query := (&PackageMetricsClient{config: plmq.config}).Query()
	for _, opt := range opts {
		opt(query)
	}
	plmq.withPackageMetrics = query
	return plmq
}

// 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.PackageLoadMetrics.Query().
//		GroupBy(packageloadmetrics.FieldName).
//		Aggregate(ent.Count()).
//		Scan(ctx, &v)
func (plmq *PackageLoadMetricsQuery) GroupBy(field string, fields ...string) *PackageLoadMetricsGroupBy {
	plmq.ctx.Fields = append([]string{field}, fields...)
	grbuild := &PackageLoadMetricsGroupBy{build: plmq}
	grbuild.flds = &plmq.ctx.Fields
	grbuild.label = packageloadmetrics.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.PackageLoadMetrics.Query().
//		Select(packageloadmetrics.FieldName).
//		Scan(ctx, &v)
func (plmq *PackageLoadMetricsQuery) Select(fields ...string) *PackageLoadMetricsSelect {
	plmq.ctx.Fields = append(plmq.ctx.Fields, fields...)
	sbuild := &PackageLoadMetricsSelect{PackageLoadMetricsQuery: plmq}
	sbuild.label = packageloadmetrics.Label
	sbuild.flds, sbuild.scan = &plmq.ctx.Fields, sbuild.Scan
	return sbuild
}

// Aggregate returns a PackageLoadMetricsSelect configured with the given aggregations.
func (plmq *PackageLoadMetricsQuery) Aggregate(fns ...AggregateFunc) *PackageLoadMetricsSelect {
	return plmq.Select().Aggregate(fns...)
}

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

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

func (plmq *PackageLoadMetricsQuery) loadPackageMetrics(ctx context.Context, query *PackageMetricsQuery, nodes []*PackageLoadMetrics, init func(*PackageLoadMetrics), assign func(*PackageLoadMetrics, *PackageMetrics)) error {
	ids := make([]int, 0, len(nodes))
	nodeids := make(map[int][]*PackageLoadMetrics)
	for i := range nodes {
		if nodes[i].package_metrics_package_load_metrics == nil {
			continue
		}
		fk := *nodes[i].package_metrics_package_load_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(packagemetrics.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 "package_metrics_package_load_metrics" returned %v`, n.ID)
		}
		for i := range nodes {
			assign(nodes[i], n)
		}
	}
	return nil
}

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

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

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

// PackageLoadMetricsGroupBy is the group-by builder for PackageLoadMetrics entities.
type PackageLoadMetricsGroupBy struct {
	selector
	build *PackageLoadMetricsQuery
}

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

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

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

// PackageLoadMetricsSelect is the builder for selecting fields of PackageLoadMetrics entities.
type PackageLoadMetricsSelect struct {
	*PackageLoadMetricsQuery
	selector
}

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

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

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