// 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/directlink"
	"github.com/cloudreve/Cloudreve/v4/ent/file"
	"github.com/cloudreve/Cloudreve/v4/ent/predicate"
)

// DirectLinkQuery is the builder for querying DirectLink entities.
type DirectLinkQuery struct {
	config
	ctx        *QueryContext
	order      []directlink.OrderOption
	inters     []Interceptor
	predicates []predicate.DirectLink
	withFile   *FileQuery
	// intermediate query (i.e. traversal path).
	sql  *sql.Selector
	path func(context.Context) (*sql.Selector, error)
}

// Where adds a new predicate for the DirectLinkQuery builder.
func (dlq *DirectLinkQuery) Where(ps ...predicate.DirectLink) *DirectLinkQuery {
	dlq.predicates = append(dlq.predicates, ps...)
	return dlq
}

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

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

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

// Order specifies how the records should be ordered.
func (dlq *DirectLinkQuery) Order(o ...directlink.OrderOption) *DirectLinkQuery {
	dlq.order = append(dlq.order, o...)
	return dlq
}

// QueryFile chains the current query on the "file" edge.
func (dlq *DirectLinkQuery) QueryFile() *FileQuery {
	query := (&FileClient{config: dlq.config}).Query()
	query.path = func(ctx context.Context) (fromU *sql.Selector, err error) {
		if err := dlq.prepareQuery(ctx); err != nil {
			return nil, err
		}
		selector := dlq.sqlQuery(ctx)
		if err := selector.Err(); err != nil {
			return nil, err
		}
		step := sqlgraph.NewStep(
			sqlgraph.From(directlink.Table, directlink.FieldID, selector),
			sqlgraph.To(file.Table, file.FieldID),
			sqlgraph.Edge(sqlgraph.M2O, true, directlink.FileTable, directlink.FileColumn),
		)
		fromU = sqlgraph.SetNeighbors(dlq.driver.Dialect(), step)
		return fromU, nil
	}
	return query
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

// WithFile tells the query-builder to eager-load the nodes that are connected to
// the "file" edge. The optional arguments are used to configure the query builder of the edge.
func (dlq *DirectLinkQuery) WithFile(opts ...func(*FileQuery)) *DirectLinkQuery {
	query := (&FileClient{config: dlq.config}).Query()
	for _, opt := range opts {
		opt(query)
	}
	dlq.withFile = query
	return dlq
}

// 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.DirectLink.Query().
//		GroupBy(directlink.FieldCreatedAt).
//		Aggregate(ent.Count()).
//		Scan(ctx, &v)
func (dlq *DirectLinkQuery) GroupBy(field string, fields ...string) *DirectLinkGroupBy {
	dlq.ctx.Fields = append([]string{field}, fields...)
	grbuild := &DirectLinkGroupBy{build: dlq}
	grbuild.flds = &dlq.ctx.Fields
	grbuild.label = directlink.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.DirectLink.Query().
//		Select(directlink.FieldCreatedAt).
//		Scan(ctx, &v)
func (dlq *DirectLinkQuery) Select(fields ...string) *DirectLinkSelect {
	dlq.ctx.Fields = append(dlq.ctx.Fields, fields...)
	sbuild := &DirectLinkSelect{DirectLinkQuery: dlq}
	sbuild.label = directlink.Label
	sbuild.flds, sbuild.scan = &dlq.ctx.Fields, sbuild.Scan
	return sbuild
}

// Aggregate returns a DirectLinkSelect configured with the given aggregations.
func (dlq *DirectLinkQuery) Aggregate(fns ...AggregateFunc) *DirectLinkSelect {
	return dlq.Select().Aggregate(fns...)
}

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

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

func (dlq *DirectLinkQuery) loadFile(ctx context.Context, query *FileQuery, nodes []*DirectLink, init func(*DirectLink), assign func(*DirectLink, *File)) error {
	ids := make([]int, 0, len(nodes))
	nodeids := make(map[int][]*DirectLink)
	for i := range nodes {
		fk := nodes[i].FileID
		if _, ok := nodeids[fk]; !ok {
			ids = append(ids, fk)
		}
		nodeids[fk] = append(nodeids[fk], nodes[i])
	}
	if len(ids) == 0 {
		return nil
	}
	query.Where(file.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 "file_id" returned %v`, n.ID)
		}
		for i := range nodes {
			assign(nodes[i], n)
		}
	}
	return nil
}

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

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

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

// DirectLinkGroupBy is the group-by builder for DirectLink entities.
type DirectLinkGroupBy struct {
	selector
	build *DirectLinkQuery
}

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

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

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

// DirectLinkSelect is the builder for selecting fields of DirectLink entities.
type DirectLinkSelect struct {
	*DirectLinkQuery
	selector
}

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

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

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