// Code generated by ent, DO NOT EDIT.

package ent

import (
	"context"
	"fmt"
	"math"

	"entgo.io/ent/dialect/sql"
	"entgo.io/ent/dialect/sql/sqlgraph"
	"entgo.io/ent/schema/field"
	"github.com/google/uuid"
	"github.com/lunabrain-ai/lunabrain/pkg/ent/group"
	"github.com/lunabrain-ai/lunabrain/pkg/ent/groupinvite"
	"github.com/lunabrain-ai/lunabrain/pkg/ent/predicate"
)

// GroupInviteQuery is the builder for querying GroupInvite entities.
type GroupInviteQuery struct {
	config
	ctx        *QueryContext
	order      []groupinvite.OrderOption
	inters     []Interceptor
	predicates []predicate.GroupInvite
	withGroup  *GroupQuery
	withFKs    bool
	// intermediate query (i.e. traversal path).
	sql  *sql.Selector
	path func(context.Context) (*sql.Selector, error)
}

// Where adds a new predicate for the GroupInviteQuery builder.
func (giq *GroupInviteQuery) Where(ps ...predicate.GroupInvite) *GroupInviteQuery {
	giq.predicates = append(giq.predicates, ps...)
	return giq
}

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

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

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

// Order specifies how the records should be ordered.
func (giq *GroupInviteQuery) Order(o ...groupinvite.OrderOption) *GroupInviteQuery {
	giq.order = append(giq.order, o...)
	return giq
}

// QueryGroup chains the current query on the "group" edge.
func (giq *GroupInviteQuery) QueryGroup() *GroupQuery {
	query := (&GroupClient{config: giq.config}).Query()
	query.path = func(ctx context.Context) (fromU *sql.Selector, err error) {
		if err := giq.prepareQuery(ctx); err != nil {
			return nil, err
		}
		selector := giq.sqlQuery(ctx)
		if err := selector.Err(); err != nil {
			return nil, err
		}
		step := sqlgraph.NewStep(
			sqlgraph.From(groupinvite.Table, groupinvite.FieldID, selector),
			sqlgraph.To(group.Table, group.FieldID),
			sqlgraph.Edge(sqlgraph.M2O, true, groupinvite.GroupTable, groupinvite.GroupColumn),
		)
		fromU = sqlgraph.SetNeighbors(giq.driver.Dialect(), step)
		return fromU, nil
	}
	return query
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

// WithGroup tells the query-builder to eager-load the nodes that are connected to
// the "group" edge. The optional arguments are used to configure the query builder of the edge.
func (giq *GroupInviteQuery) WithGroup(opts ...func(*GroupQuery)) *GroupInviteQuery {
	query := (&GroupClient{config: giq.config}).Query()
	for _, opt := range opts {
		opt(query)
	}
	giq.withGroup = query
	return giq
}

// 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 {
//		Secret string `json:"secret,omitempty"`
//		Count int `json:"count,omitempty"`
//	}
//
//	client.GroupInvite.Query().
//		GroupBy(groupinvite.FieldSecret).
//		Aggregate(ent.Count()).
//		Scan(ctx, &v)
func (giq *GroupInviteQuery) GroupBy(field string, fields ...string) *GroupInviteGroupBy {
	giq.ctx.Fields = append([]string{field}, fields...)
	grbuild := &GroupInviteGroupBy{build: giq}
	grbuild.flds = &giq.ctx.Fields
	grbuild.label = groupinvite.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 {
//		Secret string `json:"secret,omitempty"`
//	}
//
//	client.GroupInvite.Query().
//		Select(groupinvite.FieldSecret).
//		Scan(ctx, &v)
func (giq *GroupInviteQuery) Select(fields ...string) *GroupInviteSelect {
	giq.ctx.Fields = append(giq.ctx.Fields, fields...)
	sbuild := &GroupInviteSelect{GroupInviteQuery: giq}
	sbuild.label = groupinvite.Label
	sbuild.flds, sbuild.scan = &giq.ctx.Fields, sbuild.Scan
	return sbuild
}

// Aggregate returns a GroupInviteSelect configured with the given aggregations.
func (giq *GroupInviteQuery) Aggregate(fns ...AggregateFunc) *GroupInviteSelect {
	return giq.Select().Aggregate(fns...)
}

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

func (giq *GroupInviteQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*GroupInvite, error) {
	var (
		nodes       = []*GroupInvite{}
		withFKs     = giq.withFKs
		_spec       = giq.querySpec()
		loadedTypes = [1]bool{
			giq.withGroup != nil,
		}
	)
	if giq.withGroup != nil {
		withFKs = true
	}
	if withFKs {
		_spec.Node.Columns = append(_spec.Node.Columns, groupinvite.ForeignKeys...)
	}
	_spec.ScanValues = func(columns []string) ([]any, error) {
		return (*GroupInvite).scanValues(nil, columns)
	}
	_spec.Assign = func(columns []string, values []any) error {
		node := &GroupInvite{config: giq.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, giq.driver, _spec); err != nil {
		return nil, err
	}
	if len(nodes) == 0 {
		return nodes, nil
	}
	if query := giq.withGroup; query != nil {
		if err := giq.loadGroup(ctx, query, nodes, nil,
			func(n *GroupInvite, e *Group) { n.Edges.Group = e }); err != nil {
			return nil, err
		}
	}
	return nodes, nil
}

func (giq *GroupInviteQuery) loadGroup(ctx context.Context, query *GroupQuery, nodes []*GroupInvite, init func(*GroupInvite), assign func(*GroupInvite, *Group)) error {
	ids := make([]uuid.UUID, 0, len(nodes))
	nodeids := make(map[uuid.UUID][]*GroupInvite)
	for i := range nodes {
		if nodes[i].group_invites == nil {
			continue
		}
		fk := *nodes[i].group_invites
		if _, ok := nodeids[fk]; !ok {
			ids = append(ids, fk)
		}
		nodeids[fk] = append(nodeids[fk], nodes[i])
	}
	if len(ids) == 0 {
		return nil
	}
	query.Where(group.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 "group_invites" returned %v`, n.ID)
		}
		for i := range nodes {
			assign(nodes[i], n)
		}
	}
	return nil
}

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

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

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

// GroupInviteGroupBy is the group-by builder for GroupInvite entities.
type GroupInviteGroupBy struct {
	selector
	build *GroupInviteQuery
}

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

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

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

// GroupInviteSelect is the builder for selecting fields of GroupInvite entities.
type GroupInviteSelect struct {
	*GroupInviteQuery
	selector
}

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

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

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