// Code generated by ent, DO NOT EDIT.

package ent

import (
	"context"
	"fmt"
	"math"

	"entgo.io/ent/dialect/sql"
	"entgo.io/ent/dialect/sql/sqlgraph"
	"entgo.io/ent/schema/field"
	"github.com/cloudreve/Cloudreve/v4/ent/davaccount"
	"github.com/cloudreve/Cloudreve/v4/ent/predicate"
	"github.com/cloudreve/Cloudreve/v4/ent/user"
)

// DavAccountQuery is the builder for querying DavAccount entities.
type DavAccountQuery struct {
	config
	ctx        *QueryContext
	order      []davaccount.OrderOption
	inters     []Interceptor
	predicates []predicate.DavAccount
	withOwner  *UserQuery
	// intermediate query (i.e. traversal path).
	sql  *sql.Selector
	path func(context.Context) (*sql.Selector, error)
}

// Where adds a new predicate for the DavAccountQuery builder.
func (daq *DavAccountQuery) Where(ps ...predicate.DavAccount) *DavAccountQuery {
	daq.predicates = append(daq.predicates, ps...)
	return daq
}

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

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

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

// Order specifies how the records should be ordered.
func (daq *DavAccountQuery) Order(o ...davaccount.OrderOption) *DavAccountQuery {
	daq.order = append(daq.order, o...)
	return daq
}

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

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

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

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

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

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

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

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

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

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

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

// IDs executes the query and returns a list of DavAccount IDs.
func (daq *DavAccountQuery) IDs(ctx context.Context) (ids []int, err error) {
	if daq.ctx.Unique == nil && daq.path != nil {
		daq.Unique(true)
	}
	ctx = setContextOp(ctx, daq.ctx, "IDs")
	if err = daq.Select(davaccount.FieldID).Scan(ctx, &ids); err != nil {
		return nil, err
	}
	return ids, nil
}

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

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

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

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

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

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

// 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 {
//		CreatedAt time.Time `json:"created_at,omitempty"`
//		Count int `json:"count,omitempty"`
//	}
//
//	client.DavAccount.Query().
//		GroupBy(davaccount.FieldCreatedAt).
//		Aggregate(ent.Count()).
//		Scan(ctx, &v)
func (daq *DavAccountQuery) GroupBy(field string, fields ...string) *DavAccountGroupBy {
	daq.ctx.Fields = append([]string{field}, fields...)
	grbuild := &DavAccountGroupBy{build: daq}
	grbuild.flds = &daq.ctx.Fields
	grbuild.label = davaccount.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 {
//		CreatedAt time.Time `json:"created_at,omitempty"`
//	}
//
//	client.DavAccount.Query().
//		Select(davaccount.FieldCreatedAt).
//		Scan(ctx, &v)
func (daq *DavAccountQuery) Select(fields ...string) *DavAccountSelect {
	daq.ctx.Fields = append(daq.ctx.Fields, fields...)
	sbuild := &DavAccountSelect{DavAccountQuery: daq}
	sbuild.label = davaccount.Label
	sbuild.flds, sbuild.scan = &daq.ctx.Fields, sbuild.Scan
	return sbuild
}

// Aggregate returns a DavAccountSelect configured with the given aggregations.
func (daq *DavAccountQuery) Aggregate(fns ...AggregateFunc) *DavAccountSelect {
	return daq.Select().Aggregate(fns...)
}

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

func (daq *DavAccountQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*DavAccount, error) {
	var (
		nodes       = []*DavAccount{}
		_spec       = daq.querySpec()
		loadedTypes = [1]bool{
			daq.withOwner != nil,
		}
	)
	_spec.ScanValues = func(columns []string) ([]any, error) {
		return (*DavAccount).scanValues(nil, columns)
	}
	_spec.Assign = func(columns []string, values []any) error {
		node := &DavAccount{config: daq.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, daq.driver, _spec); err != nil {
		return nil, err
	}
	if len(nodes) == 0 {
		return nodes, nil
	}
	if query := daq.withOwner; query != nil {
		if err := daq.loadOwner(ctx, query, nodes, nil,
			func(n *DavAccount, e *User) { n.Edges.Owner = e }); err != nil {
			return nil, err
		}
	}
	return nodes, nil
}

func (daq *DavAccountQuery) loadOwner(ctx context.Context, query *UserQuery, nodes []*DavAccount, init func(*DavAccount), assign func(*DavAccount, *User)) error {
	ids := make([]int, 0, len(nodes))
	nodeids := make(map[int][]*DavAccount)
	for i := range nodes {
		fk := nodes[i].OwnerID
		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 "owner_id" returned %v`, n.ID)
		}
		for i := range nodes {
			assign(nodes[i], n)
		}
	}
	return nil
}

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

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

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

// DavAccountGroupBy is the group-by builder for DavAccount entities.
type DavAccountGroupBy struct {
	selector
	build *DavAccountQuery
}

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

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

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

// DavAccountSelect is the builder for selecting fields of DavAccount entities.
type DavAccountSelect struct {
	*DavAccountQuery
	selector
}

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

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

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