// Code generated by ent, DO NOT EDIT.

package ent

import (
	"context"
	"database/sql/driver"
	"fmt"
	"math"
	"wechat-api/ent/predicate"
	"wechat-api/ent/sopstage"
	"wechat-api/ent/soptask"

	"entgo.io/ent/dialect/sql"
	"entgo.io/ent/dialect/sql/sqlgraph"
	"entgo.io/ent/schema/field"
)

// SopTaskQuery is the builder for querying SopTask entities.
type SopTaskQuery struct {
	config
	ctx            *QueryContext
	order          []soptask.OrderOption
	inters         []Interceptor
	predicates     []predicate.SopTask
	withTaskStages *SopStageQuery
	// intermediate query (i.e. traversal path).
	sql  *sql.Selector
	path func(context.Context) (*sql.Selector, error)
}

// Where adds a new predicate for the SopTaskQuery builder.
func (stq *SopTaskQuery) Where(ps ...predicate.SopTask) *SopTaskQuery {
	stq.predicates = append(stq.predicates, ps...)
	return stq
}

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

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

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

// Order specifies how the records should be ordered.
func (stq *SopTaskQuery) Order(o ...soptask.OrderOption) *SopTaskQuery {
	stq.order = append(stq.order, o...)
	return stq
}

// QueryTaskStages chains the current query on the "task_stages" edge.
func (stq *SopTaskQuery) QueryTaskStages() *SopStageQuery {
	query := (&SopStageClient{config: stq.config}).Query()
	query.path = func(ctx context.Context) (fromU *sql.Selector, err error) {
		if err := stq.prepareQuery(ctx); err != nil {
			return nil, err
		}
		selector := stq.sqlQuery(ctx)
		if err := selector.Err(); err != nil {
			return nil, err
		}
		step := sqlgraph.NewStep(
			sqlgraph.From(soptask.Table, soptask.FieldID, selector),
			sqlgraph.To(sopstage.Table, sopstage.FieldID),
			sqlgraph.Edge(sqlgraph.O2M, false, soptask.TaskStagesTable, soptask.TaskStagesColumn),
		)
		fromU = sqlgraph.SetNeighbors(stq.driver.Dialect(), step)
		return fromU, nil
	}
	return query
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

// WithTaskStages tells the query-builder to eager-load the nodes that are connected to
// the "task_stages" edge. The optional arguments are used to configure the query builder of the edge.
func (stq *SopTaskQuery) WithTaskStages(opts ...func(*SopStageQuery)) *SopTaskQuery {
	query := (&SopStageClient{config: stq.config}).Query()
	for _, opt := range opts {
		opt(query)
	}
	stq.withTaskStages = query
	return stq
}

// 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.SopTask.Query().
//		GroupBy(soptask.FieldCreatedAt).
//		Aggregate(ent.Count()).
//		Scan(ctx, &v)
func (stq *SopTaskQuery) GroupBy(field string, fields ...string) *SopTaskGroupBy {
	stq.ctx.Fields = append([]string{field}, fields...)
	grbuild := &SopTaskGroupBy{build: stq}
	grbuild.flds = &stq.ctx.Fields
	grbuild.label = soptask.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.SopTask.Query().
//		Select(soptask.FieldCreatedAt).
//		Scan(ctx, &v)
func (stq *SopTaskQuery) Select(fields ...string) *SopTaskSelect {
	stq.ctx.Fields = append(stq.ctx.Fields, fields...)
	sbuild := &SopTaskSelect{SopTaskQuery: stq}
	sbuild.label = soptask.Label
	sbuild.flds, sbuild.scan = &stq.ctx.Fields, sbuild.Scan
	return sbuild
}

// Aggregate returns a SopTaskSelect configured with the given aggregations.
func (stq *SopTaskQuery) Aggregate(fns ...AggregateFunc) *SopTaskSelect {
	return stq.Select().Aggregate(fns...)
}

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

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

func (stq *SopTaskQuery) loadTaskStages(ctx context.Context, query *SopStageQuery, nodes []*SopTask, init func(*SopTask), assign func(*SopTask, *SopStage)) error {
	fks := make([]driver.Value, 0, len(nodes))
	nodeids := make(map[uint64]*SopTask)
	for i := range nodes {
		fks = append(fks, nodes[i].ID)
		nodeids[nodes[i].ID] = nodes[i]
		if init != nil {
			init(nodes[i])
		}
	}
	if len(query.ctx.Fields) > 0 {
		query.ctx.AppendFieldOnce(sopstage.FieldTaskID)
	}
	query.Where(predicate.SopStage(func(s *sql.Selector) {
		s.Where(sql.InValues(s.C(soptask.TaskStagesColumn), fks...))
	}))
	neighbors, err := query.All(ctx)
	if err != nil {
		return err
	}
	for _, n := range neighbors {
		fk := n.TaskID
		node, ok := nodeids[fk]
		if !ok {
			return fmt.Errorf(`unexpected referenced foreign-key "task_id" returned %v for node %v`, fk, n.ID)
		}
		assign(node, n)
	}
	return nil
}

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

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

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

// SopTaskGroupBy is the group-by builder for SopTask entities.
type SopTaskGroupBy struct {
	selector
	build *SopTaskQuery
}

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

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

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

// SopTaskSelect is the builder for selecting fields of SopTask entities.
type SopTaskSelect struct {
	*SopTaskQuery
	selector
}

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

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

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