// Code generated by ent, DO NOT EDIT.

package db

import (
	"context"
	"fmt"
	"math"

	"entgo.io/ent"
	"entgo.io/ent/dialect"
	"entgo.io/ent/dialect/sql"
	"entgo.io/ent/dialect/sql/sqlgraph"
	"entgo.io/ent/schema/field"
	"github.com/chaitin/MonkeyCode/backend/db/billingquota"
	"github.com/chaitin/MonkeyCode/backend/db/predicate"
)

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

// Where adds a new predicate for the BillingQuotaQuery builder.
func (bqq *BillingQuotaQuery) Where(ps ...predicate.BillingQuota) *BillingQuotaQuery {
	bqq.predicates = append(bqq.predicates, ps...)
	return bqq
}

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

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

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

// Order specifies how the records should be ordered.
func (bqq *BillingQuotaQuery) Order(o ...billingquota.OrderOption) *BillingQuotaQuery {
	bqq.order = append(bqq.order, o...)
	return bqq
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

// Exist returns true if the query has elements in the graph.
func (bqq *BillingQuotaQuery) Exist(ctx context.Context) (bool, error) {
	ctx = setContextOp(ctx, bqq.ctx, ent.OpQueryExist)
	switch _, err := bqq.FirstID(ctx); {
	case IsNotFound(err):
		return false, nil
	case err != nil:
		return false, fmt.Errorf("db: check existence: %w", err)
	default:
		return true, nil
	}
}

// ExistX is like Exist, but panics if an error occurs.
func (bqq *BillingQuotaQuery) ExistX(ctx context.Context) bool {
	exist, err := bqq.Exist(ctx)
	if err != nil {
		panic(err)
	}
	return exist
}

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

// 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 {
//		DeletedAt time.Time `json:"deleted_at,omitempty"`
//		Count int `json:"count,omitempty"`
//	}
//
//	client.BillingQuota.Query().
//		GroupBy(billingquota.FieldDeletedAt).
//		Aggregate(db.Count()).
//		Scan(ctx, &v)
func (bqq *BillingQuotaQuery) GroupBy(field string, fields ...string) *BillingQuotaGroupBy {
	bqq.ctx.Fields = append([]string{field}, fields...)
	grbuild := &BillingQuotaGroupBy{build: bqq}
	grbuild.flds = &bqq.ctx.Fields
	grbuild.label = billingquota.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 {
//		DeletedAt time.Time `json:"deleted_at,omitempty"`
//	}
//
//	client.BillingQuota.Query().
//		Select(billingquota.FieldDeletedAt).
//		Scan(ctx, &v)
func (bqq *BillingQuotaQuery) Select(fields ...string) *BillingQuotaSelect {
	bqq.ctx.Fields = append(bqq.ctx.Fields, fields...)
	sbuild := &BillingQuotaSelect{BillingQuotaQuery: bqq}
	sbuild.label = billingquota.Label
	sbuild.flds, sbuild.scan = &bqq.ctx.Fields, sbuild.Scan
	return sbuild
}

// Aggregate returns a BillingQuotaSelect configured with the given aggregations.
func (bqq *BillingQuotaQuery) Aggregate(fns ...AggregateFunc) *BillingQuotaSelect {
	return bqq.Select().Aggregate(fns...)
}

func (bqq *BillingQuotaQuery) prepareQuery(ctx context.Context) error {
	for _, inter := range bqq.inters {
		if inter == nil {
			return fmt.Errorf("db: uninitialized interceptor (forgotten import db/runtime?)")
		}
		if trv, ok := inter.(Traverser); ok {
			if err := trv.Traverse(ctx, bqq); err != nil {
				return err
			}
		}
	}
	for _, f := range bqq.ctx.Fields {
		if !billingquota.ValidColumn(f) {
			return &ValidationError{Name: f, err: fmt.Errorf("db: invalid field %q for query", f)}
		}
	}
	if bqq.path != nil {
		prev, err := bqq.path(ctx)
		if err != nil {
			return err
		}
		bqq.sql = prev
	}
	return nil
}

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

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

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

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

// ForUpdate locks the selected rows against concurrent updates, and prevent them from being
// updated, deleted or "selected ... for update" by other sessions, until the transaction is
// either committed or rolled-back.
func (bqq *BillingQuotaQuery) ForUpdate(opts ...sql.LockOption) *BillingQuotaQuery {
	if bqq.driver.Dialect() == dialect.Postgres {
		bqq.Unique(false)
	}
	bqq.modifiers = append(bqq.modifiers, func(s *sql.Selector) {
		s.ForUpdate(opts...)
	})
	return bqq
}

// ForShare behaves similarly to ForUpdate, except that it acquires a shared mode lock
// on any rows that are read. Other sessions can read the rows, but cannot modify them
// until your transaction commits.
func (bqq *BillingQuotaQuery) ForShare(opts ...sql.LockOption) *BillingQuotaQuery {
	if bqq.driver.Dialect() == dialect.Postgres {
		bqq.Unique(false)
	}
	bqq.modifiers = append(bqq.modifiers, func(s *sql.Selector) {
		s.ForShare(opts...)
	})
	return bqq
}

// Modify adds a query modifier for attaching custom logic to queries.
func (bqq *BillingQuotaQuery) Modify(modifiers ...func(s *sql.Selector)) *BillingQuotaSelect {
	bqq.modifiers = append(bqq.modifiers, modifiers...)
	return bqq.Select()
}

// BillingQuotaGroupBy is the group-by builder for BillingQuota entities.
type BillingQuotaGroupBy struct {
	selector
	build *BillingQuotaQuery
}

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

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

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

// BillingQuotaSelect is the builder for selecting fields of BillingQuota entities.
type BillingQuotaSelect struct {
	*BillingQuotaQuery
	selector
}

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

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

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

// Modify adds a query modifier for attaching custom logic to queries.
func (bqs *BillingQuotaSelect) Modify(modifiers ...func(s *sql.Selector)) *BillingQuotaSelect {
	bqs.modifiers = append(bqs.modifiers, modifiers...)
	return bqs
}
