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

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

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

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

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

// Order specifies how the records should be ordered.
func (brq *BillingRecordQuery) Order(o ...billingrecord.OrderOption) *BillingRecordQuery {
	brq.order = append(brq.order, o...)
	return brq
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

// Aggregate returns a BillingRecordSelect configured with the given aggregations.
func (brq *BillingRecordQuery) Aggregate(fns ...AggregateFunc) *BillingRecordSelect {
	return brq.Select().Aggregate(fns...)
}

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

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

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

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

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

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

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

// BillingRecordGroupBy is the group-by builder for BillingRecord entities.
type BillingRecordGroupBy struct {
	selector
	build *BillingRecordQuery
}

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

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

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

// BillingRecordSelect is the builder for selecting fields of BillingRecord entities.
type BillingRecordSelect struct {
	*BillingRecordQuery
	selector
}

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

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

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