// Code generated by ent, DO NOT EDIT.

package ent

import (
	"context"
	"fmt"
	"galileo/ent/apitag"
	"galileo/ent/predicate"
	"math"

	"entgo.io/ent/dialect/sql"
	"entgo.io/ent/dialect/sql/sqlgraph"
	"entgo.io/ent/schema/field"
)

// ApiTagQuery is the builder for querying ApiTag entities.
type ApiTagQuery struct {
	config
	ctx        *QueryContext
	order      []OrderFunc
	inters     []Interceptor
	predicates []predicate.ApiTag
	// intermediate query (i.e. traversal path).
	sql  *sql.Selector
	path func(context.Context) (*sql.Selector, error)
}

// Where adds a new predicate for the ApiTagQuery builder.
func (atq *ApiTagQuery) Where(ps ...predicate.ApiTag) *ApiTagQuery {
	atq.predicates = append(atq.predicates, ps...)
	return atq
}

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

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

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

// Order specifies how the records should be ordered.
func (atq *ApiTagQuery) Order(o ...OrderFunc) *ApiTagQuery {
	atq.order = append(atq.order, o...)
	return atq
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

// 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.ApiTag.Query().
//		GroupBy(apitag.FieldName).
//		Aggregate(ent.Count()).
//		Scan(ctx, &v)
func (atq *ApiTagQuery) GroupBy(field string, fields ...string) *ApiTagGroupBy {
	atq.ctx.Fields = append([]string{field}, fields...)
	grbuild := &ApiTagGroupBy{build: atq}
	grbuild.flds = &atq.ctx.Fields
	grbuild.label = apitag.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.ApiTag.Query().
//		Select(apitag.FieldName).
//		Scan(ctx, &v)
func (atq *ApiTagQuery) Select(fields ...string) *ApiTagSelect {
	atq.ctx.Fields = append(atq.ctx.Fields, fields...)
	sbuild := &ApiTagSelect{ApiTagQuery: atq}
	sbuild.label = apitag.Label
	sbuild.flds, sbuild.scan = &atq.ctx.Fields, sbuild.Scan
	return sbuild
}

// Aggregate returns a ApiTagSelect configured with the given aggregations.
func (atq *ApiTagQuery) Aggregate(fns ...AggregateFunc) *ApiTagSelect {
	return atq.Select().Aggregate(fns...)
}

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

func (atq *ApiTagQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*ApiTag, error) {
	var (
		nodes = []*ApiTag{}
		_spec = atq.querySpec()
	)
	_spec.ScanValues = func(columns []string) ([]any, error) {
		return (*ApiTag).scanValues(nil, columns)
	}
	_spec.Assign = func(columns []string, values []any) error {
		node := &ApiTag{config: atq.config}
		nodes = append(nodes, node)
		return node.assignValues(columns, values)
	}
	for i := range hooks {
		hooks[i](ctx, _spec)
	}
	if err := sqlgraph.QueryNodes(ctx, atq.driver, _spec); err != nil {
		return nil, err
	}
	if len(nodes) == 0 {
		return nodes, nil
	}
	return nodes, nil
}

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

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

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

// ApiTagGroupBy is the group-by builder for ApiTag entities.
type ApiTagGroupBy struct {
	selector
	build *ApiTagQuery
}

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

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

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

// ApiTagSelect is the builder for selecting fields of ApiTag entities.
type ApiTagSelect struct {
	*ApiTagQuery
	selector
}

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

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

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