// Code generated by ent, DO NOT EDIT.

package ent

import (
	"PasswordManager/ent/predicate"
	"PasswordManager/ent/user"
	"PasswordManager/ent/webauthnregisterchallenge"
	"context"
	"fmt"
	"math"

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

// WebAuthnRegisterChallengeQuery is the builder for querying WebAuthnRegisterChallenge entities.
type WebAuthnRegisterChallengeQuery struct {
	config
	ctx        *QueryContext
	order      []OrderFunc
	inters     []Interceptor
	predicates []predicate.WebAuthnRegisterChallenge
	withUser   *UserQuery
	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 WebAuthnRegisterChallengeQuery builder.
func (warcq *WebAuthnRegisterChallengeQuery) Where(ps ...predicate.WebAuthnRegisterChallenge) *WebAuthnRegisterChallengeQuery {
	warcq.predicates = append(warcq.predicates, ps...)
	return warcq
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

// Clone returns a duplicate of the WebAuthnRegisterChallengeQuery builder, including all associated steps. It can be
// used to prepare common query builders and use them differently after the clone is made.
func (warcq *WebAuthnRegisterChallengeQuery) Clone() *WebAuthnRegisterChallengeQuery {
	if warcq == nil {
		return nil
	}
	return &WebAuthnRegisterChallengeQuery{
		config:     warcq.config,
		ctx:        warcq.ctx.Clone(),
		order:      append([]OrderFunc{}, warcq.order...),
		inters:     append([]Interceptor{}, warcq.inters...),
		predicates: append([]predicate.WebAuthnRegisterChallenge{}, warcq.predicates...),
		withUser:   warcq.withUser.Clone(),
		// clone intermediate query.
		sql:  warcq.sql.Clone(),
		path: warcq.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 (warcq *WebAuthnRegisterChallengeQuery) WithUser(opts ...func(*UserQuery)) *WebAuthnRegisterChallengeQuery {
	query := (&UserClient{config: warcq.config}).Query()
	for _, opt := range opts {
		opt(query)
	}
	warcq.withUser = query
	return warcq
}

// 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 {
//		SdChallenge string `json:"sdChallenge,omitempty"`
//		Count int `json:"count,omitempty"`
//	}
//
//	client.WebAuthnRegisterChallenge.Query().
//		GroupBy(webauthnregisterchallenge.FieldSdChallenge).
//		Aggregate(ent.Count()).
//		Scan(ctx, &v)
func (warcq *WebAuthnRegisterChallengeQuery) GroupBy(field string, fields ...string) *WebAuthnRegisterChallengeGroupBy {
	warcq.ctx.Fields = append([]string{field}, fields...)
	grbuild := &WebAuthnRegisterChallengeGroupBy{build: warcq}
	grbuild.flds = &warcq.ctx.Fields
	grbuild.label = webauthnregisterchallenge.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 {
//		SdChallenge string `json:"sdChallenge,omitempty"`
//	}
//
//	client.WebAuthnRegisterChallenge.Query().
//		Select(webauthnregisterchallenge.FieldSdChallenge).
//		Scan(ctx, &v)
func (warcq *WebAuthnRegisterChallengeQuery) Select(fields ...string) *WebAuthnRegisterChallengeSelect {
	warcq.ctx.Fields = append(warcq.ctx.Fields, fields...)
	sbuild := &WebAuthnRegisterChallengeSelect{WebAuthnRegisterChallengeQuery: warcq}
	sbuild.label = webauthnregisterchallenge.Label
	sbuild.flds, sbuild.scan = &warcq.ctx.Fields, sbuild.Scan
	return sbuild
}

// Aggregate returns a WebAuthnRegisterChallengeSelect configured with the given aggregations.
func (warcq *WebAuthnRegisterChallengeQuery) Aggregate(fns ...AggregateFunc) *WebAuthnRegisterChallengeSelect {
	return warcq.Select().Aggregate(fns...)
}

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

func (warcq *WebAuthnRegisterChallengeQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*WebAuthnRegisterChallenge, error) {
	var (
		nodes       = []*WebAuthnRegisterChallenge{}
		withFKs     = warcq.withFKs
		_spec       = warcq.querySpec()
		loadedTypes = [1]bool{
			warcq.withUser != nil,
		}
	)
	if warcq.withUser != nil {
		withFKs = true
	}
	if withFKs {
		_spec.Node.Columns = append(_spec.Node.Columns, webauthnregisterchallenge.ForeignKeys...)
	}
	_spec.ScanValues = func(columns []string) ([]any, error) {
		return (*WebAuthnRegisterChallenge).scanValues(nil, columns)
	}
	_spec.Assign = func(columns []string, values []any) error {
		node := &WebAuthnRegisterChallenge{config: warcq.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, warcq.driver, _spec); err != nil {
		return nil, err
	}
	if len(nodes) == 0 {
		return nodes, nil
	}
	if query := warcq.withUser; query != nil {
		if err := warcq.loadUser(ctx, query, nodes, nil,
			func(n *WebAuthnRegisterChallenge, e *User) { n.Edges.User = e }); err != nil {
			return nil, err
		}
	}
	return nodes, nil
}

func (warcq *WebAuthnRegisterChallengeQuery) loadUser(ctx context.Context, query *UserQuery, nodes []*WebAuthnRegisterChallenge, init func(*WebAuthnRegisterChallenge), assign func(*WebAuthnRegisterChallenge, *User)) error {
	ids := make([]uuid.UUID, 0, len(nodes))
	nodeids := make(map[uuid.UUID][]*WebAuthnRegisterChallenge)
	for i := range nodes {
		if nodes[i].user_webauthn_register_challenges == nil {
			continue
		}
		fk := *nodes[i].user_webauthn_register_challenges
		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_webauthn_register_challenges" returned %v`, n.ID)
		}
		for i := range nodes {
			assign(nodes[i], n)
		}
	}
	return nil
}

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

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

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

// WebAuthnRegisterChallengeGroupBy is the group-by builder for WebAuthnRegisterChallenge entities.
type WebAuthnRegisterChallengeGroupBy struct {
	selector
	build *WebAuthnRegisterChallengeQuery
}

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

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

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

// WebAuthnRegisterChallengeSelect is the builder for selecting fields of WebAuthnRegisterChallenge entities.
type WebAuthnRegisterChallengeSelect struct {
	*WebAuthnRegisterChallengeQuery
	selector
}

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

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

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