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

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

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

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

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

// Order specifies how the records should be ordered.
func (icq *InviteCodeQuery) Order(o ...invitecode.OrderOption) *InviteCodeQuery {
	icq.order = append(icq.order, o...)
	return icq
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

// 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 {
//		AdminID uuid.UUID `json:"admin_id,omitempty"`
//		Count int `json:"count,omitempty"`
//	}
//
//	client.InviteCode.Query().
//		GroupBy(invitecode.FieldAdminID).
//		Aggregate(db.Count()).
//		Scan(ctx, &v)
func (icq *InviteCodeQuery) GroupBy(field string, fields ...string) *InviteCodeGroupBy {
	icq.ctx.Fields = append([]string{field}, fields...)
	grbuild := &InviteCodeGroupBy{build: icq}
	grbuild.flds = &icq.ctx.Fields
	grbuild.label = invitecode.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 {
//		AdminID uuid.UUID `json:"admin_id,omitempty"`
//	}
//
//	client.InviteCode.Query().
//		Select(invitecode.FieldAdminID).
//		Scan(ctx, &v)
func (icq *InviteCodeQuery) Select(fields ...string) *InviteCodeSelect {
	icq.ctx.Fields = append(icq.ctx.Fields, fields...)
	sbuild := &InviteCodeSelect{InviteCodeQuery: icq}
	sbuild.label = invitecode.Label
	sbuild.flds, sbuild.scan = &icq.ctx.Fields, sbuild.Scan
	return sbuild
}

// Aggregate returns a InviteCodeSelect configured with the given aggregations.
func (icq *InviteCodeQuery) Aggregate(fns ...AggregateFunc) *InviteCodeSelect {
	return icq.Select().Aggregate(fns...)
}

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

func (icq *InviteCodeQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*InviteCode, error) {
	var (
		nodes = []*InviteCode{}
		_spec = icq.querySpec()
	)
	_spec.ScanValues = func(columns []string) ([]any, error) {
		return (*InviteCode).scanValues(nil, columns)
	}
	_spec.Assign = func(columns []string, values []any) error {
		node := &InviteCode{config: icq.config}
		nodes = append(nodes, node)
		return node.assignValues(columns, values)
	}
	if len(icq.modifiers) > 0 {
		_spec.Modifiers = icq.modifiers
	}
	for i := range hooks {
		hooks[i](ctx, _spec)
	}
	if err := sqlgraph.QueryNodes(ctx, icq.driver, _spec); err != nil {
		return nil, err
	}
	if len(nodes) == 0 {
		return nodes, nil
	}
	return nodes, nil
}

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

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

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

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

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

// InviteCodeGroupBy is the group-by builder for InviteCode entities.
type InviteCodeGroupBy struct {
	selector
	build *InviteCodeQuery
}

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

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

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

// InviteCodeSelect is the builder for selecting fields of InviteCode entities.
type InviteCodeSelect struct {
	*InviteCodeQuery
	selector
}

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

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

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