// Copyright 2019-present Facebook Inc. All rights reserved.
// This source code is licensed under the Apache 2.0 license found
// in the LICENSE file in the root directory of this source tree.

// Code generated by ent, DO NOT EDIT.

package ent

import (
	"context"
	"fmt"
	"math"

	"entgo.io/ent/dialect/sql"
	"entgo.io/ent/dialect/sql/sqlgraph"
	"entgo.io/ent/entc/integration/edgeschema/ent/attachedfile"
	"entgo.io/ent/entc/integration/edgeschema/ent/file"
	"entgo.io/ent/entc/integration/edgeschema/ent/predicate"
	"entgo.io/ent/entc/integration/edgeschema/ent/process"
	"entgo.io/ent/schema/field"
)

// AttachedFileQuery is the builder for querying AttachedFile entities.
type AttachedFileQuery struct {
	config
	ctx        *QueryContext
	order      []attachedfile.Order
	inters     []Interceptor
	predicates []predicate.AttachedFile
	withFi     *FileQuery
	withProc   *ProcessQuery
	// intermediate query (i.e. traversal path).
	sql  *sql.Selector
	path func(context.Context) (*sql.Selector, error)
}

// Where adds a new predicate for the AttachedFileQuery builder.
func (afq *AttachedFileQuery) Where(ps ...predicate.AttachedFile) *AttachedFileQuery {
	afq.predicates = append(afq.predicates, ps...)
	return afq
}

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

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

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

// Order specifies how the records should be ordered.
func (afq *AttachedFileQuery) Order(o ...attachedfile.Order) *AttachedFileQuery {
	afq.order = append(afq.order, o...)
	return afq
}

// QueryFi chains the current query on the "fi" edge.
func (afq *AttachedFileQuery) QueryFi() *FileQuery {
	query := (&FileClient{config: afq.config}).Query()
	query.path = func(ctx context.Context) (fromU *sql.Selector, err error) {
		if err := afq.prepareQuery(ctx); err != nil {
			return nil, err
		}
		selector := afq.sqlQuery(ctx)
		if err := selector.Err(); err != nil {
			return nil, err
		}
		step := sqlgraph.NewStep(
			sqlgraph.From(attachedfile.Table, attachedfile.FieldID, selector),
			sqlgraph.To(file.Table, file.FieldID),
			sqlgraph.Edge(sqlgraph.M2O, false, attachedfile.FiTable, attachedfile.FiColumn),
		)
		fromU = sqlgraph.SetNeighbors(afq.driver.Dialect(), step)
		return fromU, nil
	}
	return query
}

// QueryProc chains the current query on the "proc" edge.
func (afq *AttachedFileQuery) QueryProc() *ProcessQuery {
	query := (&ProcessClient{config: afq.config}).Query()
	query.path = func(ctx context.Context) (fromU *sql.Selector, err error) {
		if err := afq.prepareQuery(ctx); err != nil {
			return nil, err
		}
		selector := afq.sqlQuery(ctx)
		if err := selector.Err(); err != nil {
			return nil, err
		}
		step := sqlgraph.NewStep(
			sqlgraph.From(attachedfile.Table, attachedfile.FieldID, selector),
			sqlgraph.To(process.Table, process.FieldID),
			sqlgraph.Edge(sqlgraph.M2O, false, attachedfile.ProcTable, attachedfile.ProcColumn),
		)
		fromU = sqlgraph.SetNeighbors(afq.driver.Dialect(), step)
		return fromU, nil
	}
	return query
}

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

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

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

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

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

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

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

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

// All executes the query and returns a list of AttachedFiles.
func (afq *AttachedFileQuery) All(ctx context.Context) ([]*AttachedFile, error) {
	ctx = setContextOp(ctx, afq.ctx, "All")
	if err := afq.prepareQuery(ctx); err != nil {
		return nil, err
	}
	qr := querierAll[[]*AttachedFile, *AttachedFileQuery]()
	return withInterceptors[[]*AttachedFile](ctx, afq, qr, afq.inters)
}

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

// IDs executes the query and returns a list of AttachedFile IDs.
func (afq *AttachedFileQuery) IDs(ctx context.Context) (ids []int, err error) {
	if afq.ctx.Unique == nil && afq.path != nil {
		afq.Unique(true)
	}
	ctx = setContextOp(ctx, afq.ctx, "IDs")
	if err = afq.Select(attachedfile.FieldID).Scan(ctx, &ids); err != nil {
		return nil, err
	}
	return ids, nil
}

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

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

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

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

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

// WithFi tells the query-builder to eager-load the nodes that are connected to
// the "fi" edge. The optional arguments are used to configure the query builder of the edge.
func (afq *AttachedFileQuery) WithFi(opts ...func(*FileQuery)) *AttachedFileQuery {
	query := (&FileClient{config: afq.config}).Query()
	for _, opt := range opts {
		opt(query)
	}
	afq.withFi = query
	return afq
}

// WithProc tells the query-builder to eager-load the nodes that are connected to
// the "proc" edge. The optional arguments are used to configure the query builder of the edge.
func (afq *AttachedFileQuery) WithProc(opts ...func(*ProcessQuery)) *AttachedFileQuery {
	query := (&ProcessClient{config: afq.config}).Query()
	for _, opt := range opts {
		opt(query)
	}
	afq.withProc = query
	return afq
}

// 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 {
//		AttachTime time.Time `json:"attach_time,omitempty"`
//		Count int `json:"count,omitempty"`
//	}
//
//	client.AttachedFile.Query().
//		GroupBy(attachedfile.FieldAttachTime).
//		Aggregate(ent.Count()).
//		Scan(ctx, &v)
func (afq *AttachedFileQuery) GroupBy(field string, fields ...string) *AttachedFileGroupBy {
	afq.ctx.Fields = append([]string{field}, fields...)
	grbuild := &AttachedFileGroupBy{build: afq}
	grbuild.flds = &afq.ctx.Fields
	grbuild.label = attachedfile.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 {
//		AttachTime time.Time `json:"attach_time,omitempty"`
//	}
//
//	client.AttachedFile.Query().
//		Select(attachedfile.FieldAttachTime).
//		Scan(ctx, &v)
func (afq *AttachedFileQuery) Select(fields ...string) *AttachedFileSelect {
	afq.ctx.Fields = append(afq.ctx.Fields, fields...)
	sbuild := &AttachedFileSelect{AttachedFileQuery: afq}
	sbuild.label = attachedfile.Label
	sbuild.flds, sbuild.scan = &afq.ctx.Fields, sbuild.Scan
	return sbuild
}

// Aggregate returns a AttachedFileSelect configured with the given aggregations.
func (afq *AttachedFileQuery) Aggregate(fns ...AggregateFunc) *AttachedFileSelect {
	return afq.Select().Aggregate(fns...)
}

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

func (afq *AttachedFileQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*AttachedFile, error) {
	var (
		nodes       = []*AttachedFile{}
		_spec       = afq.querySpec()
		loadedTypes = [2]bool{
			afq.withFi != nil,
			afq.withProc != nil,
		}
	)
	_spec.ScanValues = func(columns []string) ([]any, error) {
		return (*AttachedFile).scanValues(nil, columns)
	}
	_spec.Assign = func(columns []string, values []any) error {
		node := &AttachedFile{config: afq.config}
		nodes = append(nodes, node)
		node.Edges.loadedTypes = loadedTypes
		return node.assignValues(columns, values)
	}
	for i := range hooks {
		hooks[i](ctx, _spec)
	}
	if err := sqlgraph.QueryNodes(ctx, afq.driver, _spec); err != nil {
		return nil, err
	}
	if len(nodes) == 0 {
		return nodes, nil
	}
	if query := afq.withFi; query != nil {
		if err := afq.loadFi(ctx, query, nodes, nil,
			func(n *AttachedFile, e *File) { n.Edges.Fi = e }); err != nil {
			return nil, err
		}
	}
	if query := afq.withProc; query != nil {
		if err := afq.loadProc(ctx, query, nodes, nil,
			func(n *AttachedFile, e *Process) { n.Edges.Proc = e }); err != nil {
			return nil, err
		}
	}
	return nodes, nil
}

func (afq *AttachedFileQuery) loadFi(ctx context.Context, query *FileQuery, nodes []*AttachedFile, init func(*AttachedFile), assign func(*AttachedFile, *File)) error {
	ids := make([]int, 0, len(nodes))
	nodeids := make(map[int][]*AttachedFile)
	for i := range nodes {
		fk := nodes[i].FID
		if _, ok := nodeids[fk]; !ok {
			ids = append(ids, fk)
		}
		nodeids[fk] = append(nodeids[fk], nodes[i])
	}
	if len(ids) == 0 {
		return nil
	}
	query.Where(file.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 "f_id" returned %v`, n.ID)
		}
		for i := range nodes {
			assign(nodes[i], n)
		}
	}
	return nil
}
func (afq *AttachedFileQuery) loadProc(ctx context.Context, query *ProcessQuery, nodes []*AttachedFile, init func(*AttachedFile), assign func(*AttachedFile, *Process)) error {
	ids := make([]int, 0, len(nodes))
	nodeids := make(map[int][]*AttachedFile)
	for i := range nodes {
		fk := nodes[i].ProcID
		if _, ok := nodeids[fk]; !ok {
			ids = append(ids, fk)
		}
		nodeids[fk] = append(nodeids[fk], nodes[i])
	}
	if len(ids) == 0 {
		return nil
	}
	query.Where(process.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 "proc_id" returned %v`, n.ID)
		}
		for i := range nodes {
			assign(nodes[i], n)
		}
	}
	return nil
}

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

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

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

// AttachedFileGroupBy is the group-by builder for AttachedFile entities.
type AttachedFileGroupBy struct {
	selector
	build *AttachedFileQuery
}

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

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

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

// AttachedFileSelect is the builder for selecting fields of AttachedFile entities.
type AttachedFileSelect struct {
	*AttachedFileQuery
	selector
}

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

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

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