// Code generated by ent, DO NOT EDIT.

package db

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/chaitin/MonkeyCode/backend/db/codesnippet"
	"github.com/chaitin/MonkeyCode/backend/db/predicate"
	"github.com/chaitin/MonkeyCode/backend/db/workspacefile"
	"github.com/google/uuid"
)

// CodeSnippetQuery is the builder for querying CodeSnippet entities.
type CodeSnippetQuery struct {
	config
	ctx            *QueryContext
	order          []codesnippet.OrderOption
	inters         []Interceptor
	predicates     []predicate.CodeSnippet
	withSourceFile *WorkspaceFileQuery
	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 CodeSnippetQuery builder.
func (csq *CodeSnippetQuery) Where(ps ...predicate.CodeSnippet) *CodeSnippetQuery {
	csq.predicates = append(csq.predicates, ps...)
	return csq
}

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

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

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

// Order specifies how the records should be ordered.
func (csq *CodeSnippetQuery) Order(o ...codesnippet.OrderOption) *CodeSnippetQuery {
	csq.order = append(csq.order, o...)
	return csq
}

// QuerySourceFile chains the current query on the "source_file" edge.
func (csq *CodeSnippetQuery) QuerySourceFile() *WorkspaceFileQuery {
	query := (&WorkspaceFileClient{config: csq.config}).Query()
	query.path = func(ctx context.Context) (fromU *sql.Selector, err error) {
		if err := csq.prepareQuery(ctx); err != nil {
			return nil, err
		}
		selector := csq.sqlQuery(ctx)
		if err := selector.Err(); err != nil {
			return nil, err
		}
		step := sqlgraph.NewStep(
			sqlgraph.From(codesnippet.Table, codesnippet.FieldID, selector),
			sqlgraph.To(workspacefile.Table, workspacefile.FieldID),
			sqlgraph.Edge(sqlgraph.M2O, true, codesnippet.SourceFileTable, codesnippet.SourceFileColumn),
		)
		fromU = sqlgraph.SetNeighbors(csq.driver.Dialect(), step)
		return fromU, nil
	}
	return query
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

// Exist returns true if the query has elements in the graph.
func (csq *CodeSnippetQuery) Exist(ctx context.Context) (bool, error) {
	ctx = setContextOp(ctx, csq.ctx, ent.OpQueryExist)
	switch _, err := csq.FirstID(ctx); {
	case IsNotFound(err):
		return false, nil
	case err != nil:
		return false, fmt.Errorf("db: check existence: %w", err)
	default:
		return true, nil
	}
}

// ExistX is like Exist, but panics if an error occurs.
func (csq *CodeSnippetQuery) ExistX(ctx context.Context) bool {
	exist, err := csq.Exist(ctx)
	if err != nil {
		panic(err)
	}
	return exist
}

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

// WithSourceFile tells the query-builder to eager-load the nodes that are connected to
// the "source_file" edge. The optional arguments are used to configure the query builder of the edge.
func (csq *CodeSnippetQuery) WithSourceFile(opts ...func(*WorkspaceFileQuery)) *CodeSnippetQuery {
	query := (&WorkspaceFileClient{config: csq.config}).Query()
	for _, opt := range opts {
		opt(query)
	}
	csq.withSourceFile = query
	return csq
}

// 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 {
//		WorkspaceFileID uuid.UUID `json:"workspace_file_id,omitempty"`
//		Count int `json:"count,omitempty"`
//	}
//
//	client.CodeSnippet.Query().
//		GroupBy(codesnippet.FieldWorkspaceFileID).
//		Aggregate(db.Count()).
//		Scan(ctx, &v)
func (csq *CodeSnippetQuery) GroupBy(field string, fields ...string) *CodeSnippetGroupBy {
	csq.ctx.Fields = append([]string{field}, fields...)
	grbuild := &CodeSnippetGroupBy{build: csq}
	grbuild.flds = &csq.ctx.Fields
	grbuild.label = codesnippet.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 {
//		WorkspaceFileID uuid.UUID `json:"workspace_file_id,omitempty"`
//	}
//
//	client.CodeSnippet.Query().
//		Select(codesnippet.FieldWorkspaceFileID).
//		Scan(ctx, &v)
func (csq *CodeSnippetQuery) Select(fields ...string) *CodeSnippetSelect {
	csq.ctx.Fields = append(csq.ctx.Fields, fields...)
	sbuild := &CodeSnippetSelect{CodeSnippetQuery: csq}
	sbuild.label = codesnippet.Label
	sbuild.flds, sbuild.scan = &csq.ctx.Fields, sbuild.Scan
	return sbuild
}

// Aggregate returns a CodeSnippetSelect configured with the given aggregations.
func (csq *CodeSnippetQuery) Aggregate(fns ...AggregateFunc) *CodeSnippetSelect {
	return csq.Select().Aggregate(fns...)
}

func (csq *CodeSnippetQuery) prepareQuery(ctx context.Context) error {
	for _, inter := range csq.inters {
		if inter == nil {
			return fmt.Errorf("db: uninitialized interceptor (forgotten import db/runtime?)")
		}
		if trv, ok := inter.(Traverser); ok {
			if err := trv.Traverse(ctx, csq); err != nil {
				return err
			}
		}
	}
	for _, f := range csq.ctx.Fields {
		if !codesnippet.ValidColumn(f) {
			return &ValidationError{Name: f, err: fmt.Errorf("db: invalid field %q for query", f)}
		}
	}
	if csq.path != nil {
		prev, err := csq.path(ctx)
		if err != nil {
			return err
		}
		csq.sql = prev
	}
	return nil
}

func (csq *CodeSnippetQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*CodeSnippet, error) {
	var (
		nodes       = []*CodeSnippet{}
		_spec       = csq.querySpec()
		loadedTypes = [1]bool{
			csq.withSourceFile != nil,
		}
	)
	_spec.ScanValues = func(columns []string) ([]any, error) {
		return (*CodeSnippet).scanValues(nil, columns)
	}
	_spec.Assign = func(columns []string, values []any) error {
		node := &CodeSnippet{config: csq.config}
		nodes = append(nodes, node)
		node.Edges.loadedTypes = loadedTypes
		return node.assignValues(columns, values)
	}
	if len(csq.modifiers) > 0 {
		_spec.Modifiers = csq.modifiers
	}
	for i := range hooks {
		hooks[i](ctx, _spec)
	}
	if err := sqlgraph.QueryNodes(ctx, csq.driver, _spec); err != nil {
		return nil, err
	}
	if len(nodes) == 0 {
		return nodes, nil
	}
	if query := csq.withSourceFile; query != nil {
		if err := csq.loadSourceFile(ctx, query, nodes, nil,
			func(n *CodeSnippet, e *WorkspaceFile) { n.Edges.SourceFile = e }); err != nil {
			return nil, err
		}
	}
	return nodes, nil
}

func (csq *CodeSnippetQuery) loadSourceFile(ctx context.Context, query *WorkspaceFileQuery, nodes []*CodeSnippet, init func(*CodeSnippet), assign func(*CodeSnippet, *WorkspaceFile)) error {
	ids := make([]uuid.UUID, 0, len(nodes))
	nodeids := make(map[uuid.UUID][]*CodeSnippet)
	for i := range nodes {
		fk := nodes[i].WorkspaceFileID
		if _, ok := nodeids[fk]; !ok {
			ids = append(ids, fk)
		}
		nodeids[fk] = append(nodeids[fk], nodes[i])
	}
	if len(ids) == 0 {
		return nil
	}
	query.Where(workspacefile.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 "workspace_file_id" returned %v`, n.ID)
		}
		for i := range nodes {
			assign(nodes[i], n)
		}
	}
	return nil
}

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

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

func (csq *CodeSnippetQuery) sqlQuery(ctx context.Context) *sql.Selector {
	builder := sql.Dialect(csq.driver.Dialect())
	t1 := builder.Table(codesnippet.Table)
	columns := csq.ctx.Fields
	if len(columns) == 0 {
		columns = codesnippet.Columns
	}
	selector := builder.Select(t1.Columns(columns...)...).From(t1)
	if csq.sql != nil {
		selector = csq.sql
		selector.Select(selector.Columns(columns...)...)
	}
	if csq.ctx.Unique != nil && *csq.ctx.Unique {
		selector.Distinct()
	}
	for _, m := range csq.modifiers {
		m(selector)
	}
	for _, p := range csq.predicates {
		p(selector)
	}
	for _, p := range csq.order {
		p(selector)
	}
	if offset := csq.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 := csq.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 (csq *CodeSnippetQuery) ForUpdate(opts ...sql.LockOption) *CodeSnippetQuery {
	if csq.driver.Dialect() == dialect.Postgres {
		csq.Unique(false)
	}
	csq.modifiers = append(csq.modifiers, func(s *sql.Selector) {
		s.ForUpdate(opts...)
	})
	return csq
}

// 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 (csq *CodeSnippetQuery) ForShare(opts ...sql.LockOption) *CodeSnippetQuery {
	if csq.driver.Dialect() == dialect.Postgres {
		csq.Unique(false)
	}
	csq.modifiers = append(csq.modifiers, func(s *sql.Selector) {
		s.ForShare(opts...)
	})
	return csq
}

// Modify adds a query modifier for attaching custom logic to queries.
func (csq *CodeSnippetQuery) Modify(modifiers ...func(s *sql.Selector)) *CodeSnippetSelect {
	csq.modifiers = append(csq.modifiers, modifiers...)
	return csq.Select()
}

// CodeSnippetGroupBy is the group-by builder for CodeSnippet entities.
type CodeSnippetGroupBy struct {
	selector
	build *CodeSnippetQuery
}

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

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

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

// CodeSnippetSelect is the builder for selecting fields of CodeSnippet entities.
type CodeSnippetSelect struct {
	*CodeSnippetQuery
	selector
}

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

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

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

// Modify adds a query modifier for attaching custom logic to queries.
func (css *CodeSnippetSelect) Modify(modifiers ...func(s *sql.Selector)) *CodeSnippetSelect {
	css.modifiers = append(css.modifiers, modifiers...)
	return css
}
