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

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

// Where adds a new predicate for the SourceControlQuery builder.
func (scq *SourceControlQuery) Where(ps ...predicate.SourceControl) *SourceControlQuery {
	scq.predicates = append(scq.predicates, ps...)
	return scq
}

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

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

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

// Order specifies how the records should be ordered.
func (scq *SourceControlQuery) Order(o ...sourcecontrol.OrderOption) *SourceControlQuery {
	scq.order = append(scq.order, o...)
	return scq
}

// QueryBazelInvocation chains the current query on the "bazel_invocation" edge.
func (scq *SourceControlQuery) QueryBazelInvocation() *BazelInvocationQuery {
	query := (&BazelInvocationClient{config: scq.config}).Query()
	query.path = func(ctx context.Context) (fromU *sql.Selector, err error) {
		if err := scq.prepareQuery(ctx); err != nil {
			return nil, err
		}
		selector := scq.sqlQuery(ctx)
		if err := selector.Err(); err != nil {
			return nil, err
		}
		step := sqlgraph.NewStep(
			sqlgraph.From(sourcecontrol.Table, sourcecontrol.FieldID, selector),
			sqlgraph.To(bazelinvocation.Table, bazelinvocation.FieldID),
			sqlgraph.Edge(sqlgraph.O2O, true, sourcecontrol.BazelInvocationTable, sourcecontrol.BazelInvocationColumn),
		)
		fromU = sqlgraph.SetNeighbors(scq.driver.Dialect(), step)
		return fromU, nil
	}
	return query
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

// WithBazelInvocation tells the query-builder to eager-load the nodes that are connected to
// the "bazel_invocation" edge. The optional arguments are used to configure the query builder of the edge.
func (scq *SourceControlQuery) WithBazelInvocation(opts ...func(*BazelInvocationQuery)) *SourceControlQuery {
	query := (&BazelInvocationClient{config: scq.config}).Query()
	for _, opt := range opts {
		opt(query)
	}
	scq.withBazelInvocation = query
	return scq
}

// 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 {
//		RepoURL string `json:"repo_url,omitempty"`
//		Count int `json:"count,omitempty"`
//	}
//
//	client.SourceControl.Query().
//		GroupBy(sourcecontrol.FieldRepoURL).
//		Aggregate(ent.Count()).
//		Scan(ctx, &v)
func (scq *SourceControlQuery) GroupBy(field string, fields ...string) *SourceControlGroupBy {
	scq.ctx.Fields = append([]string{field}, fields...)
	grbuild := &SourceControlGroupBy{build: scq}
	grbuild.flds = &scq.ctx.Fields
	grbuild.label = sourcecontrol.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 {
//		RepoURL string `json:"repo_url,omitempty"`
//	}
//
//	client.SourceControl.Query().
//		Select(sourcecontrol.FieldRepoURL).
//		Scan(ctx, &v)
func (scq *SourceControlQuery) Select(fields ...string) *SourceControlSelect {
	scq.ctx.Fields = append(scq.ctx.Fields, fields...)
	sbuild := &SourceControlSelect{SourceControlQuery: scq}
	sbuild.label = sourcecontrol.Label
	sbuild.flds, sbuild.scan = &scq.ctx.Fields, sbuild.Scan
	return sbuild
}

// Aggregate returns a SourceControlSelect configured with the given aggregations.
func (scq *SourceControlQuery) Aggregate(fns ...AggregateFunc) *SourceControlSelect {
	return scq.Select().Aggregate(fns...)
}

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

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

func (scq *SourceControlQuery) loadBazelInvocation(ctx context.Context, query *BazelInvocationQuery, nodes []*SourceControl, init func(*SourceControl), assign func(*SourceControl, *BazelInvocation)) error {
	ids := make([]int, 0, len(nodes))
	nodeids := make(map[int][]*SourceControl)
	for i := range nodes {
		if nodes[i].bazel_invocation_source_control == nil {
			continue
		}
		fk := *nodes[i].bazel_invocation_source_control
		if _, ok := nodeids[fk]; !ok {
			ids = append(ids, fk)
		}
		nodeids[fk] = append(nodeids[fk], nodes[i])
	}
	if len(ids) == 0 {
		return nil
	}
	query.Where(bazelinvocation.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 "bazel_invocation_source_control" returned %v`, n.ID)
		}
		for i := range nodes {
			assign(nodes[i], n)
		}
	}
	return nil
}

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

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

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

// SourceControlGroupBy is the group-by builder for SourceControl entities.
type SourceControlGroupBy struct {
	selector
	build *SourceControlQuery
}

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

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

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

// SourceControlSelect is the builder for selecting fields of SourceControl entities.
type SourceControlSelect struct {
	*SourceControlQuery
	selector
}

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

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

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