// Code generated by ent, DO NOT EDIT.

package db

import (
	"context"
	"database/sql/driver"
	"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/modelprovider"
	"github.com/chaitin/MonkeyCode/backend/db/modelprovidermodel"
	"github.com/chaitin/MonkeyCode/backend/db/predicate"
)

// ModelProviderQuery is the builder for querying ModelProvider entities.
type ModelProviderQuery struct {
	config
	ctx        *QueryContext
	order      []modelprovider.OrderOption
	inters     []Interceptor
	predicates []predicate.ModelProvider
	withModels *ModelProviderModelQuery
	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 ModelProviderQuery builder.
func (mpq *ModelProviderQuery) Where(ps ...predicate.ModelProvider) *ModelProviderQuery {
	mpq.predicates = append(mpq.predicates, ps...)
	return mpq
}

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

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

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

// Order specifies how the records should be ordered.
func (mpq *ModelProviderQuery) Order(o ...modelprovider.OrderOption) *ModelProviderQuery {
	mpq.order = append(mpq.order, o...)
	return mpq
}

// QueryModels chains the current query on the "models" edge.
func (mpq *ModelProviderQuery) QueryModels() *ModelProviderModelQuery {
	query := (&ModelProviderModelClient{config: mpq.config}).Query()
	query.path = func(ctx context.Context) (fromU *sql.Selector, err error) {
		if err := mpq.prepareQuery(ctx); err != nil {
			return nil, err
		}
		selector := mpq.sqlQuery(ctx)
		if err := selector.Err(); err != nil {
			return nil, err
		}
		step := sqlgraph.NewStep(
			sqlgraph.From(modelprovider.Table, modelprovider.FieldID, selector),
			sqlgraph.To(modelprovidermodel.Table, modelprovidermodel.FieldID),
			sqlgraph.Edge(sqlgraph.O2M, false, modelprovider.ModelsTable, modelprovider.ModelsColumn),
		)
		fromU = sqlgraph.SetNeighbors(mpq.driver.Dialect(), step)
		return fromU, nil
	}
	return query
}

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

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

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

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

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

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

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

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

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

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

// IDs executes the query and returns a list of ModelProvider IDs.
func (mpq *ModelProviderQuery) IDs(ctx context.Context) (ids []string, err error) {
	if mpq.ctx.Unique == nil && mpq.path != nil {
		mpq.Unique(true)
	}
	ctx = setContextOp(ctx, mpq.ctx, ent.OpQueryIDs)
	if err = mpq.Select(modelprovider.FieldID).Scan(ctx, &ids); err != nil {
		return nil, err
	}
	return ids, nil
}

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

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

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

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

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

// WithModels tells the query-builder to eager-load the nodes that are connected to
// the "models" edge. The optional arguments are used to configure the query builder of the edge.
func (mpq *ModelProviderQuery) WithModels(opts ...func(*ModelProviderModelQuery)) *ModelProviderQuery {
	query := (&ModelProviderModelClient{config: mpq.config}).Query()
	for _, opt := range opts {
		opt(query)
	}
	mpq.withModels = query
	return mpq
}

// 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 {
//		Name string `json:"name,omitempty"`
//		Count int `json:"count,omitempty"`
//	}
//
//	client.ModelProvider.Query().
//		GroupBy(modelprovider.FieldName).
//		Aggregate(db.Count()).
//		Scan(ctx, &v)
func (mpq *ModelProviderQuery) GroupBy(field string, fields ...string) *ModelProviderGroupBy {
	mpq.ctx.Fields = append([]string{field}, fields...)
	grbuild := &ModelProviderGroupBy{build: mpq}
	grbuild.flds = &mpq.ctx.Fields
	grbuild.label = modelprovider.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 {
//		Name string `json:"name,omitempty"`
//	}
//
//	client.ModelProvider.Query().
//		Select(modelprovider.FieldName).
//		Scan(ctx, &v)
func (mpq *ModelProviderQuery) Select(fields ...string) *ModelProviderSelect {
	mpq.ctx.Fields = append(mpq.ctx.Fields, fields...)
	sbuild := &ModelProviderSelect{ModelProviderQuery: mpq}
	sbuild.label = modelprovider.Label
	sbuild.flds, sbuild.scan = &mpq.ctx.Fields, sbuild.Scan
	return sbuild
}

// Aggregate returns a ModelProviderSelect configured with the given aggregations.
func (mpq *ModelProviderQuery) Aggregate(fns ...AggregateFunc) *ModelProviderSelect {
	return mpq.Select().Aggregate(fns...)
}

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

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

func (mpq *ModelProviderQuery) loadModels(ctx context.Context, query *ModelProviderModelQuery, nodes []*ModelProvider, init func(*ModelProvider), assign func(*ModelProvider, *ModelProviderModel)) error {
	fks := make([]driver.Value, 0, len(nodes))
	nodeids := make(map[string]*ModelProvider)
	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(modelprovidermodel.FieldProviderID)
	}
	query.Where(predicate.ModelProviderModel(func(s *sql.Selector) {
		s.Where(sql.InValues(s.C(modelprovider.ModelsColumn), fks...))
	}))
	neighbors, err := query.All(ctx)
	if err != nil {
		return err
	}
	for _, n := range neighbors {
		fk := n.ProviderID
		node, ok := nodeids[fk]
		if !ok {
			return fmt.Errorf(`unexpected referenced foreign-key "provider_id" returned %v for node %v`, fk, n.ID)
		}
		assign(node, n)
	}
	return nil
}

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

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

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

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

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

// ModelProviderGroupBy is the group-by builder for ModelProvider entities.
type ModelProviderGroupBy struct {
	selector
	build *ModelProviderQuery
}

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

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

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

// ModelProviderSelect is the builder for selecting fields of ModelProvider entities.
type ModelProviderSelect struct {
	*ModelProviderQuery
	selector
}

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

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

func (mps *ModelProviderSelect) sqlScan(ctx context.Context, root *ModelProviderQuery, v any) error {
	selector := root.sqlQuery(ctx)
	aggregation := make([]string, 0, len(mps.fns))
	for _, fn := range mps.fns {
		aggregation = append(aggregation, fn(selector))
	}
	switch n := len(*mps.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 := mps.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 (mps *ModelProviderSelect) Modify(modifiers ...func(s *sql.Selector)) *ModelProviderSelect {
	mps.modifiers = append(mps.modifiers, modifiers...)
	return mps
}
