// Code generated by ent, DO NOT EDIT.

package ent

import (
	"PasswordManager/ent/challenge"
	"PasswordManager/ent/predicate"
	"PasswordManager/ent/totpcredential"
	"PasswordManager/ent/user"
	"context"
	"fmt"
	"math"

	"entgo.io/ent/dialect/sql"
	"entgo.io/ent/dialect/sql/sqlgraph"
	"entgo.io/ent/schema/field"
	"github.com/google/uuid"
)

// TotpCredentialQuery is the builder for querying TotpCredential entities.
type TotpCredentialQuery struct {
	config
	ctx           *QueryContext
	order         []OrderFunc
	inters        []Interceptor
	predicates    []predicate.TotpCredential
	withUser      *UserQuery
	withChallenge *ChallengeQuery
	withFKs       bool
	// intermediate query (i.e. traversal path).
	sql  *sql.Selector
	path func(context.Context) (*sql.Selector, error)
}

// Where adds a new predicate for the TotpCredentialQuery builder.
func (tcq *TotpCredentialQuery) Where(ps ...predicate.TotpCredential) *TotpCredentialQuery {
	tcq.predicates = append(tcq.predicates, ps...)
	return tcq
}

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

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

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

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

// QueryUser chains the current query on the "user" edge.
func (tcq *TotpCredentialQuery) QueryUser() *UserQuery {
	query := (&UserClient{config: tcq.config}).Query()
	query.path = func(ctx context.Context) (fromU *sql.Selector, err error) {
		if err := tcq.prepareQuery(ctx); err != nil {
			return nil, err
		}
		selector := tcq.sqlQuery(ctx)
		if err := selector.Err(); err != nil {
			return nil, err
		}
		step := sqlgraph.NewStep(
			sqlgraph.From(totpcredential.Table, totpcredential.FieldID, selector),
			sqlgraph.To(user.Table, user.FieldID),
			sqlgraph.Edge(sqlgraph.O2O, true, totpcredential.UserTable, totpcredential.UserColumn),
		)
		fromU = sqlgraph.SetNeighbors(tcq.driver.Dialect(), step)
		return fromU, nil
	}
	return query
}

// QueryChallenge chains the current query on the "challenge" edge.
func (tcq *TotpCredentialQuery) QueryChallenge() *ChallengeQuery {
	query := (&ChallengeClient{config: tcq.config}).Query()
	query.path = func(ctx context.Context) (fromU *sql.Selector, err error) {
		if err := tcq.prepareQuery(ctx); err != nil {
			return nil, err
		}
		selector := tcq.sqlQuery(ctx)
		if err := selector.Err(); err != nil {
			return nil, err
		}
		step := sqlgraph.NewStep(
			sqlgraph.From(totpcredential.Table, totpcredential.FieldID, selector),
			sqlgraph.To(challenge.Table, challenge.FieldID),
			sqlgraph.Edge(sqlgraph.O2O, true, totpcredential.ChallengeTable, totpcredential.ChallengeColumn),
		)
		fromU = sqlgraph.SetNeighbors(tcq.driver.Dialect(), step)
		return fromU, nil
	}
	return query
}

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

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

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

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

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

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

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

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

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

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

// IDs executes the query and returns a list of TotpCredential IDs.
func (tcq *TotpCredentialQuery) IDs(ctx context.Context) (ids []uuid.UUID, err error) {
	if tcq.ctx.Unique == nil && tcq.path != nil {
		tcq.Unique(true)
	}
	ctx = setContextOp(ctx, tcq.ctx, "IDs")
	if err = tcq.Select(totpcredential.FieldID).Scan(ctx, &ids); err != nil {
		return nil, err
	}
	return ids, nil
}

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

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

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

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

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

// WithUser tells the query-builder to eager-load the nodes that are connected to
// the "user" edge. The optional arguments are used to configure the query builder of the edge.
func (tcq *TotpCredentialQuery) WithUser(opts ...func(*UserQuery)) *TotpCredentialQuery {
	query := (&UserClient{config: tcq.config}).Query()
	for _, opt := range opts {
		opt(query)
	}
	tcq.withUser = query
	return tcq
}

// WithChallenge tells the query-builder to eager-load the nodes that are connected to
// the "challenge" edge. The optional arguments are used to configure the query builder of the edge.
func (tcq *TotpCredentialQuery) WithChallenge(opts ...func(*ChallengeQuery)) *TotpCredentialQuery {
	query := (&ChallengeClient{config: tcq.config}).Query()
	for _, opt := range opts {
		opt(query)
	}
	tcq.withChallenge = query
	return tcq
}

// 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 {
//		Secret string `json:"secret,omitempty"`
//		Count int `json:"count,omitempty"`
//	}
//
//	client.TotpCredential.Query().
//		GroupBy(totpcredential.FieldSecret).
//		Aggregate(ent.Count()).
//		Scan(ctx, &v)
func (tcq *TotpCredentialQuery) GroupBy(field string, fields ...string) *TotpCredentialGroupBy {
	tcq.ctx.Fields = append([]string{field}, fields...)
	grbuild := &TotpCredentialGroupBy{build: tcq}
	grbuild.flds = &tcq.ctx.Fields
	grbuild.label = totpcredential.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 {
//		Secret string `json:"secret,omitempty"`
//	}
//
//	client.TotpCredential.Query().
//		Select(totpcredential.FieldSecret).
//		Scan(ctx, &v)
func (tcq *TotpCredentialQuery) Select(fields ...string) *TotpCredentialSelect {
	tcq.ctx.Fields = append(tcq.ctx.Fields, fields...)
	sbuild := &TotpCredentialSelect{TotpCredentialQuery: tcq}
	sbuild.label = totpcredential.Label
	sbuild.flds, sbuild.scan = &tcq.ctx.Fields, sbuild.Scan
	return sbuild
}

// Aggregate returns a TotpCredentialSelect configured with the given aggregations.
func (tcq *TotpCredentialQuery) Aggregate(fns ...AggregateFunc) *TotpCredentialSelect {
	return tcq.Select().Aggregate(fns...)
}

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

func (tcq *TotpCredentialQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*TotpCredential, error) {
	var (
		nodes       = []*TotpCredential{}
		withFKs     = tcq.withFKs
		_spec       = tcq.querySpec()
		loadedTypes = [2]bool{
			tcq.withUser != nil,
			tcq.withChallenge != nil,
		}
	)
	if tcq.withUser != nil || tcq.withChallenge != nil {
		withFKs = true
	}
	if withFKs {
		_spec.Node.Columns = append(_spec.Node.Columns, totpcredential.ForeignKeys...)
	}
	_spec.ScanValues = func(columns []string) ([]any, error) {
		return (*TotpCredential).scanValues(nil, columns)
	}
	_spec.Assign = func(columns []string, values []any) error {
		node := &TotpCredential{config: tcq.config}
		nodes = append(nodes, node)
		node.Edges.loadedTypes = loadedTypes
		return node.assignValues(columns, values)
	}
	for i := range hooks {
		hooks[i](ctx, _spec)
	}
	if err := sqlgraph.QueryNodes(ctx, tcq.driver, _spec); err != nil {
		return nil, err
	}
	if len(nodes) == 0 {
		return nodes, nil
	}
	if query := tcq.withUser; query != nil {
		if err := tcq.loadUser(ctx, query, nodes, nil,
			func(n *TotpCredential, e *User) { n.Edges.User = e }); err != nil {
			return nil, err
		}
	}
	if query := tcq.withChallenge; query != nil {
		if err := tcq.loadChallenge(ctx, query, nodes, nil,
			func(n *TotpCredential, e *Challenge) { n.Edges.Challenge = e }); err != nil {
			return nil, err
		}
	}
	return nodes, nil
}

func (tcq *TotpCredentialQuery) loadUser(ctx context.Context, query *UserQuery, nodes []*TotpCredential, init func(*TotpCredential), assign func(*TotpCredential, *User)) error {
	ids := make([]uuid.UUID, 0, len(nodes))
	nodeids := make(map[uuid.UUID][]*TotpCredential)
	for i := range nodes {
		if nodes[i].user_totp_credential == nil {
			continue
		}
		fk := *nodes[i].user_totp_credential
		if _, ok := nodeids[fk]; !ok {
			ids = append(ids, fk)
		}
		nodeids[fk] = append(nodeids[fk], nodes[i])
	}
	if len(ids) == 0 {
		return nil
	}
	query.Where(user.IDIn(ids...))
	neighbors, err := query.All(ctx)
	if err != nil {
		return err
	}
	for _, n := range neighbors {
		nodes, ok := nodeids[n.ID]
		if !ok {
			return fmt.Errorf(`unexpected foreign-key "user_totp_credential" returned %v`, n.ID)
		}
		for i := range nodes {
			assign(nodes[i], n)
		}
	}
	return nil
}
func (tcq *TotpCredentialQuery) loadChallenge(ctx context.Context, query *ChallengeQuery, nodes []*TotpCredential, init func(*TotpCredential), assign func(*TotpCredential, *Challenge)) error {
	ids := make([]uuid.UUID, 0, len(nodes))
	nodeids := make(map[uuid.UUID][]*TotpCredential)
	for i := range nodes {
		if nodes[i].challenge_totp_credential == nil {
			continue
		}
		fk := *nodes[i].challenge_totp_credential
		if _, ok := nodeids[fk]; !ok {
			ids = append(ids, fk)
		}
		nodeids[fk] = append(nodeids[fk], nodes[i])
	}
	if len(ids) == 0 {
		return nil
	}
	query.Where(challenge.IDIn(ids...))
	neighbors, err := query.All(ctx)
	if err != nil {
		return err
	}
	for _, n := range neighbors {
		nodes, ok := nodeids[n.ID]
		if !ok {
			return fmt.Errorf(`unexpected foreign-key "challenge_totp_credential" returned %v`, n.ID)
		}
		for i := range nodes {
			assign(nodes[i], n)
		}
	}
	return nil
}

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

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

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

// TotpCredentialGroupBy is the group-by builder for TotpCredential entities.
type TotpCredentialGroupBy struct {
	selector
	build *TotpCredentialQuery
}

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

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

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

// TotpCredentialSelect is the builder for selecting fields of TotpCredential entities.
type TotpCredentialSelect struct {
	*TotpCredentialQuery
	selector
}

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

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

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