// Code generated by ent, DO NOT EDIT.

package ent

import (
	"context"
	"fmt"
	"math"

	"entgo.io/ent"
	"entgo.io/ent/dialect"
	"entgo.io/ent/dialect/sql"
	"entgo.io/ent/dialect/sql/sqlgraph"
	"entgo.io/ent/schema/field"
	"github.com/google/uuid"
	"github.com/lightsparkdev/spark/so/ent/predicate"
	"github.com/lightsparkdev/spark/so/ent/preimagerequest"
	"github.com/lightsparkdev/spark/so/ent/preimageshare"
)

// PreimageShareQuery is the builder for querying PreimageShare entities.
type PreimageShareQuery struct {
	config
	ctx                 *QueryContext
	order               []preimageshare.OrderOption
	inters              []Interceptor
	predicates          []predicate.PreimageShare
	withPreimageRequest *PreimageRequestQuery
	withFKs             bool
	modifiers           []func(*sql.Selector)
	// intermediate query (i.e. traversal path).
	sql  *sql.Selector
	path func(context.Context) (*sql.Selector, error)
}

// Where adds a new predicate for the PreimageShareQuery builder.
func (psq *PreimageShareQuery) Where(ps ...predicate.PreimageShare) *PreimageShareQuery {
	psq.predicates = append(psq.predicates, ps...)
	return psq
}

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

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

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

// Order specifies how the records should be ordered.
func (psq *PreimageShareQuery) Order(o ...preimageshare.OrderOption) *PreimageShareQuery {
	psq.order = append(psq.order, o...)
	return psq
}

// QueryPreimageRequest chains the current query on the "preimage_request" edge.
func (psq *PreimageShareQuery) QueryPreimageRequest() *PreimageRequestQuery {
	query := (&PreimageRequestClient{config: psq.config}).Query()
	query.path = func(ctx context.Context) (fromU *sql.Selector, err error) {
		if err := psq.prepareQuery(ctx); err != nil {
			return nil, err
		}
		selector := psq.sqlQuery(ctx)
		if err := selector.Err(); err != nil {
			return nil, err
		}
		step := sqlgraph.NewStep(
			sqlgraph.From(preimageshare.Table, preimageshare.FieldID, selector),
			sqlgraph.To(preimagerequest.Table, preimagerequest.FieldID),
			sqlgraph.Edge(sqlgraph.O2O, true, preimageshare.PreimageRequestTable, preimageshare.PreimageRequestColumn),
		)
		fromU = sqlgraph.SetNeighbors(psq.driver.Dialect(), step)
		return fromU, nil
	}
	return query
}

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

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

// FirstID returns the first PreimageShare ID from the query.
// Returns a *NotFoundError when no PreimageShare ID was found.
func (psq *PreimageShareQuery) FirstID(ctx context.Context) (id uuid.UUID, err error) {
	var ids []uuid.UUID
	if ids, err = psq.Limit(1).IDs(setContextOp(ctx, psq.ctx, ent.OpQueryFirstID)); err != nil {
		return
	}
	if len(ids) == 0 {
		err = &NotFoundError{preimageshare.Label}
		return
	}
	return ids[0], nil
}

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

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

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

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

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

// All executes the query and returns a list of PreimageShares.
func (psq *PreimageShareQuery) All(ctx context.Context) ([]*PreimageShare, error) {
	ctx = setContextOp(ctx, psq.ctx, ent.OpQueryAll)
	if err := psq.prepareQuery(ctx); err != nil {
		return nil, err
	}
	qr := querierAll[[]*PreimageShare, *PreimageShareQuery]()
	return withInterceptors[[]*PreimageShare](ctx, psq, qr, psq.inters)
}

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

// IDs executes the query and returns a list of PreimageShare IDs.
func (psq *PreimageShareQuery) IDs(ctx context.Context) (ids []uuid.UUID, err error) {
	if psq.ctx.Unique == nil && psq.path != nil {
		psq.Unique(true)
	}
	ctx = setContextOp(ctx, psq.ctx, ent.OpQueryIDs)
	if err = psq.Select(preimageshare.FieldID).Scan(ctx, &ids); err != nil {
		return nil, err
	}
	return ids, nil
}

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

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

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

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

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

// WithPreimageRequest tells the query-builder to eager-load the nodes that are connected to
// the "preimage_request" edge. The optional arguments are used to configure the query builder of the edge.
func (psq *PreimageShareQuery) WithPreimageRequest(opts ...func(*PreimageRequestQuery)) *PreimageShareQuery {
	query := (&PreimageRequestClient{config: psq.config}).Query()
	for _, opt := range opts {
		opt(query)
	}
	psq.withPreimageRequest = query
	return psq
}

// 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 {
//		CreateTime time.Time `json:"create_time,omitempty"`
//		Count int `json:"count,omitempty"`
//	}
//
//	client.PreimageShare.Query().
//		GroupBy(preimageshare.FieldCreateTime).
//		Aggregate(ent.Count()).
//		Scan(ctx, &v)
func (psq *PreimageShareQuery) GroupBy(field string, fields ...string) *PreimageShareGroupBy {
	psq.ctx.Fields = append([]string{field}, fields...)
	grbuild := &PreimageShareGroupBy{build: psq}
	grbuild.flds = &psq.ctx.Fields
	grbuild.label = preimageshare.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 {
//		CreateTime time.Time `json:"create_time,omitempty"`
//	}
//
//	client.PreimageShare.Query().
//		Select(preimageshare.FieldCreateTime).
//		Scan(ctx, &v)
func (psq *PreimageShareQuery) Select(fields ...string) *PreimageShareSelect {
	psq.ctx.Fields = append(psq.ctx.Fields, fields...)
	sbuild := &PreimageShareSelect{PreimageShareQuery: psq}
	sbuild.label = preimageshare.Label
	sbuild.flds, sbuild.scan = &psq.ctx.Fields, sbuild.Scan
	return sbuild
}

// Aggregate returns a PreimageShareSelect configured with the given aggregations.
func (psq *PreimageShareQuery) Aggregate(fns ...AggregateFunc) *PreimageShareSelect {
	return psq.Select().Aggregate(fns...)
}

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

func (psq *PreimageShareQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*PreimageShare, error) {
	var (
		nodes       = []*PreimageShare{}
		withFKs     = psq.withFKs
		_spec       = psq.querySpec()
		loadedTypes = [1]bool{
			psq.withPreimageRequest != nil,
		}
	)
	if psq.withPreimageRequest != nil {
		withFKs = true
	}
	if withFKs {
		_spec.Node.Columns = append(_spec.Node.Columns, preimageshare.ForeignKeys...)
	}
	_spec.ScanValues = func(columns []string) ([]any, error) {
		return (*PreimageShare).scanValues(nil, columns)
	}
	_spec.Assign = func(columns []string, values []any) error {
		node := &PreimageShare{config: psq.config}
		nodes = append(nodes, node)
		node.Edges.loadedTypes = loadedTypes
		return node.assignValues(columns, values)
	}
	if len(psq.modifiers) > 0 {
		_spec.Modifiers = psq.modifiers
	}
	for i := range hooks {
		hooks[i](ctx, _spec)
	}
	if err := sqlgraph.QueryNodes(ctx, psq.driver, _spec); err != nil {
		return nil, err
	}
	if len(nodes) == 0 {
		return nodes, nil
	}
	if query := psq.withPreimageRequest; query != nil {
		if err := psq.loadPreimageRequest(ctx, query, nodes, nil,
			func(n *PreimageShare, e *PreimageRequest) { n.Edges.PreimageRequest = e }); err != nil {
			return nil, err
		}
	}
	return nodes, nil
}

func (psq *PreimageShareQuery) loadPreimageRequest(ctx context.Context, query *PreimageRequestQuery, nodes []*PreimageShare, init func(*PreimageShare), assign func(*PreimageShare, *PreimageRequest)) error {
	ids := make([]uuid.UUID, 0, len(nodes))
	nodeids := make(map[uuid.UUID][]*PreimageShare)
	for i := range nodes {
		if nodes[i].preimage_request_preimage_shares == nil {
			continue
		}
		fk := *nodes[i].preimage_request_preimage_shares
		if _, ok := nodeids[fk]; !ok {
			ids = append(ids, fk)
		}
		nodeids[fk] = append(nodeids[fk], nodes[i])
	}
	if len(ids) == 0 {
		return nil
	}
	query.Where(preimagerequest.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 "preimage_request_preimage_shares" returned %v`, n.ID)
		}
		for i := range nodes {
			assign(nodes[i], n)
		}
	}
	return nil
}

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

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

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

// ForUpdate locks the selected rows against concurrent updates, and prevent them from being
// updated, deleted or "selected ... for update" by other sessions, until the transaction is
// either committed or rolled-back.
func (psq *PreimageShareQuery) ForUpdate(opts ...sql.LockOption) *PreimageShareQuery {
	if psq.driver.Dialect() == dialect.Postgres {
		psq.Unique(false)
	}
	psq.modifiers = append(psq.modifiers, func(s *sql.Selector) {
		s.ForUpdate(opts...)
	})
	return psq
}

// ForShare behaves similarly to ForUpdate, except that it acquires a shared mode lock
// on any rows that are read. Other sessions can read the rows, but cannot modify them
// until your transaction commits.
func (psq *PreimageShareQuery) ForShare(opts ...sql.LockOption) *PreimageShareQuery {
	if psq.driver.Dialect() == dialect.Postgres {
		psq.Unique(false)
	}
	psq.modifiers = append(psq.modifiers, func(s *sql.Selector) {
		s.ForShare(opts...)
	})
	return psq
}

// PreimageShareGroupBy is the group-by builder for PreimageShare entities.
type PreimageShareGroupBy struct {
	selector
	build *PreimageShareQuery
}

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

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

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

// PreimageShareSelect is the builder for selecting fields of PreimageShare entities.
type PreimageShareSelect struct {
	*PreimageShareQuery
	selector
}

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

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

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