// 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/oauthclient"
	"github.com/cloudreve/Cloudreve/v4/ent/oauthgrant"
	"github.com/cloudreve/Cloudreve/v4/ent/predicate"
	"github.com/cloudreve/Cloudreve/v4/ent/user"
)

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

// Where adds a new predicate for the OAuthGrantQuery builder.
func (ogq *OAuthGrantQuery) Where(ps ...predicate.OAuthGrant) *OAuthGrantQuery {
	ogq.predicates = append(ogq.predicates, ps...)
	return ogq
}

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

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

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

// Order specifies how the records should be ordered.
func (ogq *OAuthGrantQuery) Order(o ...oauthgrant.OrderOption) *OAuthGrantQuery {
	ogq.order = append(ogq.order, o...)
	return ogq
}

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

// QueryClient chains the current query on the "client" edge.
func (ogq *OAuthGrantQuery) QueryClient() *OAuthClientQuery {
	query := (&OAuthClientClient{config: ogq.config}).Query()
	query.path = func(ctx context.Context) (fromU *sql.Selector, err error) {
		if err := ogq.prepareQuery(ctx); err != nil {
			return nil, err
		}
		selector := ogq.sqlQuery(ctx)
		if err := selector.Err(); err != nil {
			return nil, err
		}
		step := sqlgraph.NewStep(
			sqlgraph.From(oauthgrant.Table, oauthgrant.FieldID, selector),
			sqlgraph.To(oauthclient.Table, oauthclient.FieldID),
			sqlgraph.Edge(sqlgraph.M2O, true, oauthgrant.ClientTable, oauthgrant.ClientColumn),
		)
		fromU = sqlgraph.SetNeighbors(ogq.driver.Dialect(), step)
		return fromU, nil
	}
	return query
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

// WithClient tells the query-builder to eager-load the nodes that are connected to
// the "client" edge. The optional arguments are used to configure the query builder of the edge.
func (ogq *OAuthGrantQuery) WithClient(opts ...func(*OAuthClientQuery)) *OAuthGrantQuery {
	query := (&OAuthClientClient{config: ogq.config}).Query()
	for _, opt := range opts {
		opt(query)
	}
	ogq.withClient = query
	return ogq
}

// 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.OAuthGrant.Query().
//		GroupBy(oauthgrant.FieldCreatedAt).
//		Aggregate(ent.Count()).
//		Scan(ctx, &v)
func (ogq *OAuthGrantQuery) GroupBy(field string, fields ...string) *OAuthGrantGroupBy {
	ogq.ctx.Fields = append([]string{field}, fields...)
	grbuild := &OAuthGrantGroupBy{build: ogq}
	grbuild.flds = &ogq.ctx.Fields
	grbuild.label = oauthgrant.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.OAuthGrant.Query().
//		Select(oauthgrant.FieldCreatedAt).
//		Scan(ctx, &v)
func (ogq *OAuthGrantQuery) Select(fields ...string) *OAuthGrantSelect {
	ogq.ctx.Fields = append(ogq.ctx.Fields, fields...)
	sbuild := &OAuthGrantSelect{OAuthGrantQuery: ogq}
	sbuild.label = oauthgrant.Label
	sbuild.flds, sbuild.scan = &ogq.ctx.Fields, sbuild.Scan
	return sbuild
}

// Aggregate returns a OAuthGrantSelect configured with the given aggregations.
func (ogq *OAuthGrantQuery) Aggregate(fns ...AggregateFunc) *OAuthGrantSelect {
	return ogq.Select().Aggregate(fns...)
}

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

func (ogq *OAuthGrantQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*OAuthGrant, error) {
	var (
		nodes       = []*OAuthGrant{}
		_spec       = ogq.querySpec()
		loadedTypes = [2]bool{
			ogq.withUser != nil,
			ogq.withClient != nil,
		}
	)
	_spec.ScanValues = func(columns []string) ([]any, error) {
		return (*OAuthGrant).scanValues(nil, columns)
	}
	_spec.Assign = func(columns []string, values []any) error {
		node := &OAuthGrant{config: ogq.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, ogq.driver, _spec); err != nil {
		return nil, err
	}
	if len(nodes) == 0 {
		return nodes, nil
	}
	if query := ogq.withUser; query != nil {
		if err := ogq.loadUser(ctx, query, nodes, nil,
			func(n *OAuthGrant, e *User) { n.Edges.User = e }); err != nil {
			return nil, err
		}
	}
	if query := ogq.withClient; query != nil {
		if err := ogq.loadClient(ctx, query, nodes, nil,
			func(n *OAuthGrant, e *OAuthClient) { n.Edges.Client = e }); err != nil {
			return nil, err
		}
	}
	return nodes, nil
}

func (ogq *OAuthGrantQuery) loadUser(ctx context.Context, query *UserQuery, nodes []*OAuthGrant, init func(*OAuthGrant), assign func(*OAuthGrant, *User)) error {
	ids := make([]int, 0, len(nodes))
	nodeids := make(map[int][]*OAuthGrant)
	for i := range nodes {
		fk := nodes[i].UserID
		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_id" returned %v`, n.ID)
		}
		for i := range nodes {
			assign(nodes[i], n)
		}
	}
	return nil
}
func (ogq *OAuthGrantQuery) loadClient(ctx context.Context, query *OAuthClientQuery, nodes []*OAuthGrant, init func(*OAuthGrant), assign func(*OAuthGrant, *OAuthClient)) error {
	ids := make([]int, 0, len(nodes))
	nodeids := make(map[int][]*OAuthGrant)
	for i := range nodes {
		fk := nodes[i].ClientID
		if _, ok := nodeids[fk]; !ok {
			ids = append(ids, fk)
		}
		nodeids[fk] = append(nodeids[fk], nodes[i])
	}
	if len(ids) == 0 {
		return nil
	}
	query.Where(oauthclient.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 "client_id" returned %v`, n.ID)
		}
		for i := range nodes {
			assign(nodes[i], n)
		}
	}
	return nil
}

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

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

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

// OAuthGrantGroupBy is the group-by builder for OAuthGrant entities.
type OAuthGrantGroupBy struct {
	selector
	build *OAuthGrantQuery
}

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

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

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

// OAuthGrantSelect is the builder for selecting fields of OAuthGrant entities.
type OAuthGrantSelect struct {
	*OAuthGrantQuery
	selector
}

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

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

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