// Code generated by ent, DO NOT EDIT.

package ent

import (
	"context"
	"fmt"
	"math"
	"wechat-api/ent/employee"
	"wechat-api/ent/predicate"
	"wechat-api/ent/workexperience"

	"entgo.io/ent/dialect/sql"
	"entgo.io/ent/dialect/sql/sqlgraph"
	"entgo.io/ent/schema/field"
)

// WorkExperienceQuery is the builder for querying WorkExperience entities.
type WorkExperienceQuery struct {
	config
	ctx          *QueryContext
	order        []workexperience.OrderOption
	inters       []Interceptor
	predicates   []predicate.WorkExperience
	withEmployee *EmployeeQuery
	// intermediate query (i.e. traversal path).
	sql  *sql.Selector
	path func(context.Context) (*sql.Selector, error)
}

// Where adds a new predicate for the WorkExperienceQuery builder.
func (weq *WorkExperienceQuery) Where(ps ...predicate.WorkExperience) *WorkExperienceQuery {
	weq.predicates = append(weq.predicates, ps...)
	return weq
}

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

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

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

// Order specifies how the records should be ordered.
func (weq *WorkExperienceQuery) Order(o ...workexperience.OrderOption) *WorkExperienceQuery {
	weq.order = append(weq.order, o...)
	return weq
}

// QueryEmployee chains the current query on the "employee" edge.
func (weq *WorkExperienceQuery) QueryEmployee() *EmployeeQuery {
	query := (&EmployeeClient{config: weq.config}).Query()
	query.path = func(ctx context.Context) (fromU *sql.Selector, err error) {
		if err := weq.prepareQuery(ctx); err != nil {
			return nil, err
		}
		selector := weq.sqlQuery(ctx)
		if err := selector.Err(); err != nil {
			return nil, err
		}
		step := sqlgraph.NewStep(
			sqlgraph.From(workexperience.Table, workexperience.FieldID, selector),
			sqlgraph.To(employee.Table, employee.FieldID),
			sqlgraph.Edge(sqlgraph.M2O, true, workexperience.EmployeeTable, workexperience.EmployeeColumn),
		)
		fromU = sqlgraph.SetNeighbors(weq.driver.Dialect(), step)
		return fromU, nil
	}
	return query
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

// WithEmployee tells the query-builder to eager-load the nodes that are connected to
// the "employee" edge. The optional arguments are used to configure the query builder of the edge.
func (weq *WorkExperienceQuery) WithEmployee(opts ...func(*EmployeeQuery)) *WorkExperienceQuery {
	query := (&EmployeeClient{config: weq.config}).Query()
	for _, opt := range opts {
		opt(query)
	}
	weq.withEmployee = query
	return weq
}

// 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 {
//		CreatedAt time.Time `json:"created_at,omitempty"`
//		Count int `json:"count,omitempty"`
//	}
//
//	client.WorkExperience.Query().
//		GroupBy(workexperience.FieldCreatedAt).
//		Aggregate(ent.Count()).
//		Scan(ctx, &v)
func (weq *WorkExperienceQuery) GroupBy(field string, fields ...string) *WorkExperienceGroupBy {
	weq.ctx.Fields = append([]string{field}, fields...)
	grbuild := &WorkExperienceGroupBy{build: weq}
	grbuild.flds = &weq.ctx.Fields
	grbuild.label = workexperience.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 {
//		CreatedAt time.Time `json:"created_at,omitempty"`
//	}
//
//	client.WorkExperience.Query().
//		Select(workexperience.FieldCreatedAt).
//		Scan(ctx, &v)
func (weq *WorkExperienceQuery) Select(fields ...string) *WorkExperienceSelect {
	weq.ctx.Fields = append(weq.ctx.Fields, fields...)
	sbuild := &WorkExperienceSelect{WorkExperienceQuery: weq}
	sbuild.label = workexperience.Label
	sbuild.flds, sbuild.scan = &weq.ctx.Fields, sbuild.Scan
	return sbuild
}

// Aggregate returns a WorkExperienceSelect configured with the given aggregations.
func (weq *WorkExperienceQuery) Aggregate(fns ...AggregateFunc) *WorkExperienceSelect {
	return weq.Select().Aggregate(fns...)
}

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

func (weq *WorkExperienceQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*WorkExperience, error) {
	var (
		nodes       = []*WorkExperience{}
		_spec       = weq.querySpec()
		loadedTypes = [1]bool{
			weq.withEmployee != nil,
		}
	)
	_spec.ScanValues = func(columns []string) ([]any, error) {
		return (*WorkExperience).scanValues(nil, columns)
	}
	_spec.Assign = func(columns []string, values []any) error {
		node := &WorkExperience{config: weq.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, weq.driver, _spec); err != nil {
		return nil, err
	}
	if len(nodes) == 0 {
		return nodes, nil
	}
	if query := weq.withEmployee; query != nil {
		if err := weq.loadEmployee(ctx, query, nodes, nil,
			func(n *WorkExperience, e *Employee) { n.Edges.Employee = e }); err != nil {
			return nil, err
		}
	}
	return nodes, nil
}

func (weq *WorkExperienceQuery) loadEmployee(ctx context.Context, query *EmployeeQuery, nodes []*WorkExperience, init func(*WorkExperience), assign func(*WorkExperience, *Employee)) error {
	ids := make([]uint64, 0, len(nodes))
	nodeids := make(map[uint64][]*WorkExperience)
	for i := range nodes {
		fk := nodes[i].EmployeeID
		if _, ok := nodeids[fk]; !ok {
			ids = append(ids, fk)
		}
		nodeids[fk] = append(nodeids[fk], nodes[i])
	}
	if len(ids) == 0 {
		return nil
	}
	query.Where(employee.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 "employee_id" returned %v`, n.ID)
		}
		for i := range nodes {
			assign(nodes[i], n)
		}
	}
	return nil
}

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

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

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

// WorkExperienceGroupBy is the group-by builder for WorkExperience entities.
type WorkExperienceGroupBy struct {
	selector
	build *WorkExperienceQuery
}

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

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

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

// WorkExperienceSelect is the builder for selecting fields of WorkExperience entities.
type WorkExperienceSelect struct {
	*WorkExperienceQuery
	selector
}

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

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

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