// 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/schema/field"
	"github.com/google/uuid"
	"github.com/hay-kot/homebox/backend/internal/data/ent/item"
	"github.com/hay-kot/homebox/backend/internal/data/ent/itemfield"
	"github.com/hay-kot/homebox/backend/internal/data/ent/predicate"
)

// ItemFieldQuery is the builder for querying ItemField entities.
type ItemFieldQuery struct {
	config
	ctx        *QueryContext
	order      []itemfield.OrderOption
	inters     []Interceptor
	predicates []predicate.ItemField
	withItem   *ItemQuery
	withFKs    bool
	// intermediate query (i.e. traversal path).
	sql  *sql.Selector
	path func(context.Context) (*sql.Selector, error)
}

// Where adds a new predicate for the ItemFieldQuery builder.
func (ifq *ItemFieldQuery) Where(ps ...predicate.ItemField) *ItemFieldQuery {
	ifq.predicates = append(ifq.predicates, ps...)
	return ifq
}

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

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

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

// Order specifies how the records should be ordered.
func (ifq *ItemFieldQuery) Order(o ...itemfield.OrderOption) *ItemFieldQuery {
	ifq.order = append(ifq.order, o...)
	return ifq
}

// QueryItem chains the current query on the "item" edge.
func (ifq *ItemFieldQuery) QueryItem() *ItemQuery {
	query := (&ItemClient{config: ifq.config}).Query()
	query.path = func(ctx context.Context) (fromU *sql.Selector, err error) {
		if err := ifq.prepareQuery(ctx); err != nil {
			return nil, err
		}
		selector := ifq.sqlQuery(ctx)
		if err := selector.Err(); err != nil {
			return nil, err
		}
		step := sqlgraph.NewStep(
			sqlgraph.From(itemfield.Table, itemfield.FieldID, selector),
			sqlgraph.To(item.Table, item.FieldID),
			sqlgraph.Edge(sqlgraph.M2O, true, itemfield.ItemTable, itemfield.ItemColumn),
		)
		fromU = sqlgraph.SetNeighbors(ifq.driver.Dialect(), step)
		return fromU, nil
	}
	return query
}

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

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

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

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

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

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

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

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

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

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

// IDs executes the query and returns a list of ItemField IDs.
func (ifq *ItemFieldQuery) IDs(ctx context.Context) (ids []uuid.UUID, err error) {
	if ifq.ctx.Unique == nil && ifq.path != nil {
		ifq.Unique(true)
	}
	ctx = setContextOp(ctx, ifq.ctx, "IDs")
	if err = ifq.Select(itemfield.FieldID).Scan(ctx, &ids); err != nil {
		return nil, err
	}
	return ids, nil
}

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

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

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

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

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

// WithItem tells the query-builder to eager-load the nodes that are connected to
// the "item" edge. The optional arguments are used to configure the query builder of the edge.
func (ifq *ItemFieldQuery) WithItem(opts ...func(*ItemQuery)) *ItemFieldQuery {
	query := (&ItemClient{config: ifq.config}).Query()
	for _, opt := range opts {
		opt(query)
	}
	ifq.withItem = query
	return ifq
}

// 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 {
//		CreatedAt time.Time `json:"created_at,omitempty"`
//		Count int `json:"count,omitempty"`
//	}
//
//	client.ItemField.Query().
//		GroupBy(itemfield.FieldCreatedAt).
//		Aggregate(ent.Count()).
//		Scan(ctx, &v)
func (ifq *ItemFieldQuery) GroupBy(field string, fields ...string) *ItemFieldGroupBy {
	ifq.ctx.Fields = append([]string{field}, fields...)
	grbuild := &ItemFieldGroupBy{build: ifq}
	grbuild.flds = &ifq.ctx.Fields
	grbuild.label = itemfield.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 {
//		CreatedAt time.Time `json:"created_at,omitempty"`
//	}
//
//	client.ItemField.Query().
//		Select(itemfield.FieldCreatedAt).
//		Scan(ctx, &v)
func (ifq *ItemFieldQuery) Select(fields ...string) *ItemFieldSelect {
	ifq.ctx.Fields = append(ifq.ctx.Fields, fields...)
	sbuild := &ItemFieldSelect{ItemFieldQuery: ifq}
	sbuild.label = itemfield.Label
	sbuild.flds, sbuild.scan = &ifq.ctx.Fields, sbuild.Scan
	return sbuild
}

// Aggregate returns a ItemFieldSelect configured with the given aggregations.
func (ifq *ItemFieldQuery) Aggregate(fns ...AggregateFunc) *ItemFieldSelect {
	return ifq.Select().Aggregate(fns...)
}

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

func (ifq *ItemFieldQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*ItemField, error) {
	var (
		nodes       = []*ItemField{}
		withFKs     = ifq.withFKs
		_spec       = ifq.querySpec()
		loadedTypes = [1]bool{
			ifq.withItem != nil,
		}
	)
	if ifq.withItem != nil {
		withFKs = true
	}
	if withFKs {
		_spec.Node.Columns = append(_spec.Node.Columns, itemfield.ForeignKeys...)
	}
	_spec.ScanValues = func(columns []string) ([]any, error) {
		return (*ItemField).scanValues(nil, columns)
	}
	_spec.Assign = func(columns []string, values []any) error {
		node := &ItemField{config: ifq.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, ifq.driver, _spec); err != nil {
		return nil, err
	}
	if len(nodes) == 0 {
		return nodes, nil
	}
	if query := ifq.withItem; query != nil {
		if err := ifq.loadItem(ctx, query, nodes, nil,
			func(n *ItemField, e *Item) { n.Edges.Item = e }); err != nil {
			return nil, err
		}
	}
	return nodes, nil
}

func (ifq *ItemFieldQuery) loadItem(ctx context.Context, query *ItemQuery, nodes []*ItemField, init func(*ItemField), assign func(*ItemField, *Item)) error {
	ids := make([]uuid.UUID, 0, len(nodes))
	nodeids := make(map[uuid.UUID][]*ItemField)
	for i := range nodes {
		if nodes[i].item_fields == nil {
			continue
		}
		fk := *nodes[i].item_fields
		if _, ok := nodeids[fk]; !ok {
			ids = append(ids, fk)
		}
		nodeids[fk] = append(nodeids[fk], nodes[i])
	}
	if len(ids) == 0 {
		return nil
	}
	query.Where(item.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 "item_fields" returned %v`, n.ID)
		}
		for i := range nodes {
			assign(nodes[i], n)
		}
	}
	return nil
}

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

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

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

// ItemFieldGroupBy is the group-by builder for ItemField entities.
type ItemFieldGroupBy struct {
	selector
	build *ItemFieldQuery
}

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

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

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

// ItemFieldSelect is the builder for selecting fields of ItemField entities.
type ItemFieldSelect struct {
	*ItemFieldQuery
	selector
}

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

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

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