// 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/billingplan"
	"github.com/chaitin/MonkeyCode/backend/db/predicate"
)

// BillingPlanQuery is the builder for querying BillingPlan entities.
type BillingPlanQuery struct {
	config
	ctx        *QueryContext
	order      []billingplan.OrderOption
	inters     []Interceptor
	predicates []predicate.BillingPlan
	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 BillingPlanQuery builder.
func (bpq *BillingPlanQuery) Where(ps ...predicate.BillingPlan) *BillingPlanQuery {
	bpq.predicates = append(bpq.predicates, ps...)
	return bpq
}

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

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

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

// Order specifies how the records should be ordered.
func (bpq *BillingPlanQuery) Order(o ...billingplan.OrderOption) *BillingPlanQuery {
	bpq.order = append(bpq.order, o...)
	return bpq
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

// Clone returns a duplicate of the BillingPlanQuery builder, including all associated steps. It can be
// used to prepare common query builders and use them differently after the clone is made.
func (bpq *BillingPlanQuery) Clone() *BillingPlanQuery {
	if bpq == nil {
		return nil
	}
	return &BillingPlanQuery{
		config:     bpq.config,
		ctx:        bpq.ctx.Clone(),
		order:      append([]billingplan.OrderOption{}, bpq.order...),
		inters:     append([]Interceptor{}, bpq.inters...),
		predicates: append([]predicate.BillingPlan{}, bpq.predicates...),
		// clone intermediate query.
		sql:       bpq.sql.Clone(),
		path:      bpq.path,
		modifiers: append([]func(*sql.Selector){}, bpq.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 {
//		Name string `json:"name,omitempty"`
//		Count int `json:"count,omitempty"`
//	}
//
//	client.BillingPlan.Query().
//		GroupBy(billingplan.FieldName).
//		Aggregate(db.Count()).
//		Scan(ctx, &v)
func (bpq *BillingPlanQuery) GroupBy(field string, fields ...string) *BillingPlanGroupBy {
	bpq.ctx.Fields = append([]string{field}, fields...)
	grbuild := &BillingPlanGroupBy{build: bpq}
	grbuild.flds = &bpq.ctx.Fields
	grbuild.label = billingplan.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.BillingPlan.Query().
//		Select(billingplan.FieldName).
//		Scan(ctx, &v)
func (bpq *BillingPlanQuery) Select(fields ...string) *BillingPlanSelect {
	bpq.ctx.Fields = append(bpq.ctx.Fields, fields...)
	sbuild := &BillingPlanSelect{BillingPlanQuery: bpq}
	sbuild.label = billingplan.Label
	sbuild.flds, sbuild.scan = &bpq.ctx.Fields, sbuild.Scan
	return sbuild
}

// Aggregate returns a BillingPlanSelect configured with the given aggregations.
func (bpq *BillingPlanQuery) Aggregate(fns ...AggregateFunc) *BillingPlanSelect {
	return bpq.Select().Aggregate(fns...)
}

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

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

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

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

func (bpq *BillingPlanQuery) sqlQuery(ctx context.Context) *sql.Selector {
	builder := sql.Dialect(bpq.driver.Dialect())
	t1 := builder.Table(billingplan.Table)
	columns := bpq.ctx.Fields
	if len(columns) == 0 {
		columns = billingplan.Columns
	}
	selector := builder.Select(t1.Columns(columns...)...).From(t1)
	if bpq.sql != nil {
		selector = bpq.sql
		selector.Select(selector.Columns(columns...)...)
	}
	if bpq.ctx.Unique != nil && *bpq.ctx.Unique {
		selector.Distinct()
	}
	for _, m := range bpq.modifiers {
		m(selector)
	}
	for _, p := range bpq.predicates {
		p(selector)
	}
	for _, p := range bpq.order {
		p(selector)
	}
	if offset := bpq.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 := bpq.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 (bpq *BillingPlanQuery) ForUpdate(opts ...sql.LockOption) *BillingPlanQuery {
	if bpq.driver.Dialect() == dialect.Postgres {
		bpq.Unique(false)
	}
	bpq.modifiers = append(bpq.modifiers, func(s *sql.Selector) {
		s.ForUpdate(opts...)
	})
	return bpq
}

// 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 (bpq *BillingPlanQuery) ForShare(opts ...sql.LockOption) *BillingPlanQuery {
	if bpq.driver.Dialect() == dialect.Postgres {
		bpq.Unique(false)
	}
	bpq.modifiers = append(bpq.modifiers, func(s *sql.Selector) {
		s.ForShare(opts...)
	})
	return bpq
}

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

// BillingPlanGroupBy is the group-by builder for BillingPlan entities.
type BillingPlanGroupBy struct {
	selector
	build *BillingPlanQuery
}

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

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

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

// BillingPlanSelect is the builder for selecting fields of BillingPlan entities.
type BillingPlanSelect struct {
	*BillingPlanQuery
	selector
}

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

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

func (bps *BillingPlanSelect) sqlScan(ctx context.Context, root *BillingPlanQuery, v any) error {
	selector := root.sqlQuery(ctx)
	aggregation := make([]string, 0, len(bps.fns))
	for _, fn := range bps.fns {
		aggregation = append(aggregation, fn(selector))
	}
	switch n := len(*bps.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 := bps.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 (bps *BillingPlanSelect) Modify(modifiers ...func(s *sql.Selector)) *BillingPlanSelect {
	bps.modifiers = append(bps.modifiers, modifiers...)
	return bps
}
