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

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

// Where adds a new predicate for the FsEventQuery builder.
func (feq *FsEventQuery) Where(ps ...predicate.FsEvent) *FsEventQuery {
	feq.predicates = append(feq.predicates, ps...)
	return feq
}

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

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

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

// Order specifies how the records should be ordered.
func (feq *FsEventQuery) Order(o ...fsevent.OrderOption) *FsEventQuery {
	feq.order = append(feq.order, o...)
	return feq
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

// 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.FsEvent.Query().
//		GroupBy(fsevent.FieldCreatedAt).
//		Aggregate(ent.Count()).
//		Scan(ctx, &v)
func (feq *FsEventQuery) GroupBy(field string, fields ...string) *FsEventGroupBy {
	feq.ctx.Fields = append([]string{field}, fields...)
	grbuild := &FsEventGroupBy{build: feq}
	grbuild.flds = &feq.ctx.Fields
	grbuild.label = fsevent.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.FsEvent.Query().
//		Select(fsevent.FieldCreatedAt).
//		Scan(ctx, &v)
func (feq *FsEventQuery) Select(fields ...string) *FsEventSelect {
	feq.ctx.Fields = append(feq.ctx.Fields, fields...)
	sbuild := &FsEventSelect{FsEventQuery: feq}
	sbuild.label = fsevent.Label
	sbuild.flds, sbuild.scan = &feq.ctx.Fields, sbuild.Scan
	return sbuild
}

// Aggregate returns a FsEventSelect configured with the given aggregations.
func (feq *FsEventQuery) Aggregate(fns ...AggregateFunc) *FsEventSelect {
	return feq.Select().Aggregate(fns...)
}

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

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

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

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

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

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

// FsEventGroupBy is the group-by builder for FsEvent entities.
type FsEventGroupBy struct {
	selector
	build *FsEventQuery
}

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

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

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

// FsEventSelect is the builder for selecting fields of FsEvent entities.
type FsEventSelect struct {
	*FsEventQuery
	selector
}

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

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

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