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

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

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

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

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

// Order specifies how the records should be ordered.
func (buq *BillingUsageQuery) Order(o ...billingusage.OrderOption) *BillingUsageQuery {
	buq.order = append(buq.order, o...)
	return buq
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

// Clone returns a duplicate of the BillingUsageQuery builder, including all associated steps. It can be
// used to prepare common query builders and use them differently after the clone is made.
func (buq *BillingUsageQuery) Clone() *BillingUsageQuery {
	if buq == nil {
		return nil
	}
	return &BillingUsageQuery{
		config:     buq.config,
		ctx:        buq.ctx.Clone(),
		order:      append([]billingusage.OrderOption{}, buq.order...),
		inters:     append([]Interceptor{}, buq.inters...),
		predicates: append([]predicate.BillingUsage{}, buq.predicates...),
		// clone intermediate query.
		sql:       buq.sql.Clone(),
		path:      buq.path,
		modifiers: append([]func(*sql.Selector){}, buq.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.BillingUsage.Query().
//		GroupBy(billingusage.FieldDeletedAt).
//		Aggregate(db.Count()).
//		Scan(ctx, &v)
func (buq *BillingUsageQuery) GroupBy(field string, fields ...string) *BillingUsageGroupBy {
	buq.ctx.Fields = append([]string{field}, fields...)
	grbuild := &BillingUsageGroupBy{build: buq}
	grbuild.flds = &buq.ctx.Fields
	grbuild.label = billingusage.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.BillingUsage.Query().
//		Select(billingusage.FieldDeletedAt).
//		Scan(ctx, &v)
func (buq *BillingUsageQuery) Select(fields ...string) *BillingUsageSelect {
	buq.ctx.Fields = append(buq.ctx.Fields, fields...)
	sbuild := &BillingUsageSelect{BillingUsageQuery: buq}
	sbuild.label = billingusage.Label
	sbuild.flds, sbuild.scan = &buq.ctx.Fields, sbuild.Scan
	return sbuild
}

// Aggregate returns a BillingUsageSelect configured with the given aggregations.
func (buq *BillingUsageQuery) Aggregate(fns ...AggregateFunc) *BillingUsageSelect {
	return buq.Select().Aggregate(fns...)
}

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

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

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

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

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

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

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

// BillingUsageGroupBy is the group-by builder for BillingUsage entities.
type BillingUsageGroupBy struct {
	selector
	build *BillingUsageQuery
}

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

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

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

// BillingUsageSelect is the builder for selecting fields of BillingUsage entities.
type BillingUsageSelect struct {
	*BillingUsageQuery
	selector
}

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

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

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