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

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

// Where adds a new predicate for the ResourceUsageQuery builder.
func (ruq *ResourceUsageQuery) Where(ps ...predicate.ResourceUsage) *ResourceUsageQuery {
	ruq.predicates = append(ruq.predicates, ps...)
	return ruq
}

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

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

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

// Order specifies how the records should be ordered.
func (ruq *ResourceUsageQuery) Order(o ...resourceusage.OrderOption) *ResourceUsageQuery {
	ruq.order = append(ruq.order, o...)
	return ruq
}

// QueryExecutionInfo chains the current query on the "execution_info" edge.
func (ruq *ResourceUsageQuery) QueryExecutionInfo() *ExectionInfoQuery {
	query := (&ExectionInfoClient{config: ruq.config}).Query()
	query.path = func(ctx context.Context) (fromU *sql.Selector, err error) {
		if err := ruq.prepareQuery(ctx); err != nil {
			return nil, err
		}
		selector := ruq.sqlQuery(ctx)
		if err := selector.Err(); err != nil {
			return nil, err
		}
		step := sqlgraph.NewStep(
			sqlgraph.From(resourceusage.Table, resourceusage.FieldID, selector),
			sqlgraph.To(exectioninfo.Table, exectioninfo.FieldID),
			sqlgraph.Edge(sqlgraph.M2O, true, resourceusage.ExecutionInfoTable, resourceusage.ExecutionInfoColumn),
		)
		fromU = sqlgraph.SetNeighbors(ruq.driver.Dialect(), step)
		return fromU, nil
	}
	return query
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

// WithExecutionInfo tells the query-builder to eager-load the nodes that are connected to
// the "execution_info" edge. The optional arguments are used to configure the query builder of the edge.
func (ruq *ResourceUsageQuery) WithExecutionInfo(opts ...func(*ExectionInfoQuery)) *ResourceUsageQuery {
	query := (&ExectionInfoClient{config: ruq.config}).Query()
	for _, opt := range opts {
		opt(query)
	}
	ruq.withExecutionInfo = query
	return ruq
}

// 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.ResourceUsage.Query().
//		GroupBy(resourceusage.FieldName).
//		Aggregate(ent.Count()).
//		Scan(ctx, &v)
func (ruq *ResourceUsageQuery) GroupBy(field string, fields ...string) *ResourceUsageGroupBy {
	ruq.ctx.Fields = append([]string{field}, fields...)
	grbuild := &ResourceUsageGroupBy{build: ruq}
	grbuild.flds = &ruq.ctx.Fields
	grbuild.label = resourceusage.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.ResourceUsage.Query().
//		Select(resourceusage.FieldName).
//		Scan(ctx, &v)
func (ruq *ResourceUsageQuery) Select(fields ...string) *ResourceUsageSelect {
	ruq.ctx.Fields = append(ruq.ctx.Fields, fields...)
	sbuild := &ResourceUsageSelect{ResourceUsageQuery: ruq}
	sbuild.label = resourceusage.Label
	sbuild.flds, sbuild.scan = &ruq.ctx.Fields, sbuild.Scan
	return sbuild
}

// Aggregate returns a ResourceUsageSelect configured with the given aggregations.
func (ruq *ResourceUsageQuery) Aggregate(fns ...AggregateFunc) *ResourceUsageSelect {
	return ruq.Select().Aggregate(fns...)
}

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

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

func (ruq *ResourceUsageQuery) loadExecutionInfo(ctx context.Context, query *ExectionInfoQuery, nodes []*ResourceUsage, init func(*ResourceUsage), assign func(*ResourceUsage, *ExectionInfo)) error {
	ids := make([]int, 0, len(nodes))
	nodeids := make(map[int][]*ResourceUsage)
	for i := range nodes {
		if nodes[i].exection_info_resource_usage == nil {
			continue
		}
		fk := *nodes[i].exection_info_resource_usage
		if _, ok := nodeids[fk]; !ok {
			ids = append(ids, fk)
		}
		nodeids[fk] = append(nodeids[fk], nodes[i])
	}
	if len(ids) == 0 {
		return nil
	}
	query.Where(exectioninfo.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 "exection_info_resource_usage" returned %v`, n.ID)
		}
		for i := range nodes {
			assign(nodes[i], n)
		}
	}
	return nil
}

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

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

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

// ResourceUsageGroupBy is the group-by builder for ResourceUsage entities.
type ResourceUsageGroupBy struct {
	selector
	build *ResourceUsageQuery
}

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

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

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

// ResourceUsageSelect is the builder for selecting fields of ResourceUsage entities.
type ResourceUsageSelect struct {
	*ResourceUsageQuery
	selector
}

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

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

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