// Code generated by BobGen psql v0.42.5. DO NOT EDIT.
// This file is meant to be re-generated in place and/or deleted at any time.

package models

import (
	"context"
	"fmt"
	"io"

	"github.com/Gleipnir-Technology/bob"
	"github.com/Gleipnir-Technology/bob/dialect/psql"
	"github.com/Gleipnir-Technology/bob/dialect/psql/dialect"
	"github.com/Gleipnir-Technology/bob/dialect/psql/dm"
	"github.com/Gleipnir-Technology/bob/dialect/psql/sm"
	"github.com/Gleipnir-Technology/bob/dialect/psql/um"
	"github.com/Gleipnir-Technology/bob/expr"
	"github.com/Gleipnir-Technology/bob/orm"
	"github.com/Gleipnir-Technology/bob/types/pgtypes"
	"github.com/aarondl/opt/null"
	"github.com/aarondl/opt/omit"
	"github.com/aarondl/opt/omitnull"
	enums "source.gleipnir.technology/Gleipnir/nidus-sync/db/enums"
)

// ReviewTaskPool is an object representing the database table.
type ReviewTaskPool struct {
	FeaturePoolID int32                             `db:"feature_pool_id" `
	Location      null.Val[string]                  `db:"location" `
	Geometry      null.Val[string]                  `db:"geometry" `
	ReviewTaskID  int32                             `db:"review_task_id,pk" `
	Condition     null.Val[enums.Poolconditiontype] `db:"condition" `

	R reviewTaskPoolR `db:"-" `
}

// ReviewTaskPoolSlice is an alias for a slice of pointers to ReviewTaskPool.
// This should almost always be used instead of []*ReviewTaskPool.
type ReviewTaskPoolSlice []*ReviewTaskPool

// ReviewTaskPools contains methods to work with the review_task_pool table
var ReviewTaskPools = psql.NewTablex[*ReviewTaskPool, ReviewTaskPoolSlice, *ReviewTaskPoolSetter]("", "review_task_pool", buildReviewTaskPoolColumns("review_task_pool"))

// ReviewTaskPoolsQuery is a query on the review_task_pool table
type ReviewTaskPoolsQuery = *psql.ViewQuery[*ReviewTaskPool, ReviewTaskPoolSlice]

// reviewTaskPoolR is where relationships are stored.
type reviewTaskPoolR struct {
	FeaturePool *FeaturePool // review_task_pool.review_task_pool_feature_pool_fkey
	ReviewTask  *ReviewTask  // review_task_pool.review_task_pool_review_task_id_fkey
}

func buildReviewTaskPoolColumns(alias string) reviewTaskPoolColumns {
	return reviewTaskPoolColumns{
		ColumnsExpr: expr.NewColumnsExpr(
			"feature_pool_id", "location", "geometry", "review_task_id", "condition",
		).WithParent("review_task_pool"),
		tableAlias:    alias,
		FeaturePoolID: psql.Quote(alias, "feature_pool_id"),
		Location:      psql.Quote(alias, "location"),
		Geometry:      psql.Quote(alias, "geometry"),
		ReviewTaskID:  psql.Quote(alias, "review_task_id"),
		Condition:     psql.Quote(alias, "condition"),
	}
}

type reviewTaskPoolColumns struct {
	expr.ColumnsExpr
	tableAlias    string
	FeaturePoolID psql.Expression
	Location      psql.Expression
	Geometry      psql.Expression
	ReviewTaskID  psql.Expression
	Condition     psql.Expression
}

func (c reviewTaskPoolColumns) Alias() string {
	return c.tableAlias
}

func (reviewTaskPoolColumns) AliasedAs(alias string) reviewTaskPoolColumns {
	return buildReviewTaskPoolColumns(alias)
}

// ReviewTaskPoolSetter is used for insert/upsert/update operations
// All values are optional, and do not have to be set
// Generated columns are not included
type ReviewTaskPoolSetter struct {
	FeaturePoolID omit.Val[int32]                       `db:"feature_pool_id" `
	Location      omitnull.Val[string]                  `db:"location" `
	Geometry      omitnull.Val[string]                  `db:"geometry" `
	ReviewTaskID  omit.Val[int32]                       `db:"review_task_id,pk" `
	Condition     omitnull.Val[enums.Poolconditiontype] `db:"condition" `
}

func (s ReviewTaskPoolSetter) SetColumns() []string {
	vals := make([]string, 0, 5)
	if s.FeaturePoolID.IsValue() {
		vals = append(vals, "feature_pool_id")
	}
	if !s.Location.IsUnset() {
		vals = append(vals, "location")
	}
	if !s.Geometry.IsUnset() {
		vals = append(vals, "geometry")
	}
	if s.ReviewTaskID.IsValue() {
		vals = append(vals, "review_task_id")
	}
	if !s.Condition.IsUnset() {
		vals = append(vals, "condition")
	}
	return vals
}

func (s ReviewTaskPoolSetter) Overwrite(t *ReviewTaskPool) {
	if s.FeaturePoolID.IsValue() {
		t.FeaturePoolID = s.FeaturePoolID.MustGet()
	}
	if !s.Location.IsUnset() {
		t.Location = s.Location.MustGetNull()
	}
	if !s.Geometry.IsUnset() {
		t.Geometry = s.Geometry.MustGetNull()
	}
	if s.ReviewTaskID.IsValue() {
		t.ReviewTaskID = s.ReviewTaskID.MustGet()
	}
	if !s.Condition.IsUnset() {
		t.Condition = s.Condition.MustGetNull()
	}
}

func (s *ReviewTaskPoolSetter) Apply(q *dialect.InsertQuery) {
	q.AppendHooks(func(ctx context.Context, exec bob.Executor) (context.Context, error) {
		return ReviewTaskPools.BeforeInsertHooks.RunHooks(ctx, exec, s)
	})

	q.AppendValues(bob.ExpressionFunc(func(ctx context.Context, w io.StringWriter, d bob.Dialect, start int) ([]any, error) {
		vals := make([]bob.Expression, 5)
		if s.FeaturePoolID.IsValue() {
			vals[0] = psql.Arg(s.FeaturePoolID.MustGet())
		} else {
			vals[0] = psql.Raw("DEFAULT")
		}

		if !s.Location.IsUnset() {
			vals[1] = psql.Arg(s.Location.MustGetNull())
		} else {
			vals[1] = psql.Raw("DEFAULT")
		}

		if !s.Geometry.IsUnset() {
			vals[2] = psql.Arg(s.Geometry.MustGetNull())
		} else {
			vals[2] = psql.Raw("DEFAULT")
		}

		if s.ReviewTaskID.IsValue() {
			vals[3] = psql.Arg(s.ReviewTaskID.MustGet())
		} else {
			vals[3] = psql.Raw("DEFAULT")
		}

		if !s.Condition.IsUnset() {
			vals[4] = psql.Arg(s.Condition.MustGetNull())
		} else {
			vals[4] = psql.Raw("DEFAULT")
		}

		return bob.ExpressSlice(ctx, w, d, start, vals, "", ", ", "")
	}))
}

func (s ReviewTaskPoolSetter) UpdateMod() bob.Mod[*dialect.UpdateQuery] {
	return um.Set(s.Expressions()...)
}

func (s ReviewTaskPoolSetter) Expressions(prefix ...string) []bob.Expression {
	exprs := make([]bob.Expression, 0, 5)

	if s.FeaturePoolID.IsValue() {
		exprs = append(exprs, expr.Join{Sep: " = ", Exprs: []bob.Expression{
			psql.Quote(append(prefix, "feature_pool_id")...),
			psql.Arg(s.FeaturePoolID),
		}})
	}

	if !s.Location.IsUnset() {
		exprs = append(exprs, expr.Join{Sep: " = ", Exprs: []bob.Expression{
			psql.Quote(append(prefix, "location")...),
			psql.Arg(s.Location),
		}})
	}

	if !s.Geometry.IsUnset() {
		exprs = append(exprs, expr.Join{Sep: " = ", Exprs: []bob.Expression{
			psql.Quote(append(prefix, "geometry")...),
			psql.Arg(s.Geometry),
		}})
	}

	if s.ReviewTaskID.IsValue() {
		exprs = append(exprs, expr.Join{Sep: " = ", Exprs: []bob.Expression{
			psql.Quote(append(prefix, "review_task_id")...),
			psql.Arg(s.ReviewTaskID),
		}})
	}

	if !s.Condition.IsUnset() {
		exprs = append(exprs, expr.Join{Sep: " = ", Exprs: []bob.Expression{
			psql.Quote(append(prefix, "condition")...),
			psql.Arg(s.Condition),
		}})
	}

	return exprs
}

// FindReviewTaskPool retrieves a single record by primary key
// If cols is empty Find will return all columns.
func FindReviewTaskPool(ctx context.Context, exec bob.Executor, ReviewTaskIDPK int32, cols ...string) (*ReviewTaskPool, error) {
	if len(cols) == 0 {
		return ReviewTaskPools.Query(
			sm.Where(ReviewTaskPools.Columns.ReviewTaskID.EQ(psql.Arg(ReviewTaskIDPK))),
		).One(ctx, exec)
	}

	return ReviewTaskPools.Query(
		sm.Where(ReviewTaskPools.Columns.ReviewTaskID.EQ(psql.Arg(ReviewTaskIDPK))),
		sm.Columns(ReviewTaskPools.Columns.Only(cols...)),
	).One(ctx, exec)
}

// ReviewTaskPoolExists checks the presence of a single record by primary key
func ReviewTaskPoolExists(ctx context.Context, exec bob.Executor, ReviewTaskIDPK int32) (bool, error) {
	return ReviewTaskPools.Query(
		sm.Where(ReviewTaskPools.Columns.ReviewTaskID.EQ(psql.Arg(ReviewTaskIDPK))),
	).Exists(ctx, exec)
}

// AfterQueryHook is called after ReviewTaskPool is retrieved from the database
func (o *ReviewTaskPool) AfterQueryHook(ctx context.Context, exec bob.Executor, queryType bob.QueryType) error {
	var err error

	switch queryType {
	case bob.QueryTypeSelect:
		ctx, err = ReviewTaskPools.AfterSelectHooks.RunHooks(ctx, exec, ReviewTaskPoolSlice{o})
	case bob.QueryTypeInsert:
		ctx, err = ReviewTaskPools.AfterInsertHooks.RunHooks(ctx, exec, ReviewTaskPoolSlice{o})
	case bob.QueryTypeUpdate:
		ctx, err = ReviewTaskPools.AfterUpdateHooks.RunHooks(ctx, exec, ReviewTaskPoolSlice{o})
	case bob.QueryTypeDelete:
		ctx, err = ReviewTaskPools.AfterDeleteHooks.RunHooks(ctx, exec, ReviewTaskPoolSlice{o})
	}

	return err
}

// primaryKeyVals returns the primary key values of the ReviewTaskPool
func (o *ReviewTaskPool) primaryKeyVals() bob.Expression {
	return psql.Arg(o.ReviewTaskID)
}

func (o *ReviewTaskPool) pkEQ() dialect.Expression {
	return psql.Quote("review_task_pool", "review_task_id").EQ(bob.ExpressionFunc(func(ctx context.Context, w io.StringWriter, d bob.Dialect, start int) ([]any, error) {
		return o.primaryKeyVals().WriteSQL(ctx, w, d, start)
	}))
}

// Update uses an executor to update the ReviewTaskPool
func (o *ReviewTaskPool) Update(ctx context.Context, exec bob.Executor, s *ReviewTaskPoolSetter) error {
	v, err := ReviewTaskPools.Update(s.UpdateMod(), um.Where(o.pkEQ())).One(ctx, exec)
	if err != nil {
		return err
	}

	o.R = v.R
	*o = *v

	return nil
}

// Delete deletes a single ReviewTaskPool record with an executor
func (o *ReviewTaskPool) Delete(ctx context.Context, exec bob.Executor) error {
	_, err := ReviewTaskPools.Delete(dm.Where(o.pkEQ())).Exec(ctx, exec)
	return err
}

// Reload refreshes the ReviewTaskPool using the executor
func (o *ReviewTaskPool) Reload(ctx context.Context, exec bob.Executor) error {
	o2, err := ReviewTaskPools.Query(
		sm.Where(ReviewTaskPools.Columns.ReviewTaskID.EQ(psql.Arg(o.ReviewTaskID))),
	).One(ctx, exec)
	if err != nil {
		return err
	}
	o2.R = o.R
	*o = *o2

	return nil
}

// AfterQueryHook is called after ReviewTaskPoolSlice is retrieved from the database
func (o ReviewTaskPoolSlice) AfterQueryHook(ctx context.Context, exec bob.Executor, queryType bob.QueryType) error {
	var err error

	switch queryType {
	case bob.QueryTypeSelect:
		ctx, err = ReviewTaskPools.AfterSelectHooks.RunHooks(ctx, exec, o)
	case bob.QueryTypeInsert:
		ctx, err = ReviewTaskPools.AfterInsertHooks.RunHooks(ctx, exec, o)
	case bob.QueryTypeUpdate:
		ctx, err = ReviewTaskPools.AfterUpdateHooks.RunHooks(ctx, exec, o)
	case bob.QueryTypeDelete:
		ctx, err = ReviewTaskPools.AfterDeleteHooks.RunHooks(ctx, exec, o)
	}

	return err
}

func (o ReviewTaskPoolSlice) pkIN() dialect.Expression {
	if len(o) == 0 {
		return psql.Raw("NULL")
	}

	return psql.Quote("review_task_pool", "review_task_id").In(bob.ExpressionFunc(func(ctx context.Context, w io.StringWriter, d bob.Dialect, start int) ([]any, error) {
		pkPairs := make([]bob.Expression, len(o))
		for i, row := range o {
			pkPairs[i] = row.primaryKeyVals()
		}
		return bob.ExpressSlice(ctx, w, d, start, pkPairs, "", ", ", "")
	}))
}

// copyMatchingRows finds models in the given slice that have the same primary key
// then it first copies the existing relationships from the old model to the new model
// and then replaces the old model in the slice with the new model
func (o ReviewTaskPoolSlice) copyMatchingRows(from ...*ReviewTaskPool) {
	for i, old := range o {
		for _, new := range from {
			if new.ReviewTaskID != old.ReviewTaskID {
				continue
			}
			new.R = old.R
			o[i] = new
			break
		}
	}
}

// UpdateMod modifies an update query with "WHERE primary_key IN (o...)"
func (o ReviewTaskPoolSlice) UpdateMod() bob.Mod[*dialect.UpdateQuery] {
	return bob.ModFunc[*dialect.UpdateQuery](func(q *dialect.UpdateQuery) {
		q.AppendHooks(func(ctx context.Context, exec bob.Executor) (context.Context, error) {
			return ReviewTaskPools.BeforeUpdateHooks.RunHooks(ctx, exec, o)
		})

		q.AppendLoader(bob.LoaderFunc(func(ctx context.Context, exec bob.Executor, retrieved any) error {
			var err error
			switch retrieved := retrieved.(type) {
			case *ReviewTaskPool:
				o.copyMatchingRows(retrieved)
			case []*ReviewTaskPool:
				o.copyMatchingRows(retrieved...)
			case ReviewTaskPoolSlice:
				o.copyMatchingRows(retrieved...)
			default:
				// If the retrieved value is not a ReviewTaskPool or a slice of ReviewTaskPool
				// then run the AfterUpdateHooks on the slice
				_, err = ReviewTaskPools.AfterUpdateHooks.RunHooks(ctx, exec, o)
			}

			return err
		}))

		q.AppendWhere(o.pkIN())
	})
}

// DeleteMod modifies an delete query with "WHERE primary_key IN (o...)"
func (o ReviewTaskPoolSlice) DeleteMod() bob.Mod[*dialect.DeleteQuery] {
	return bob.ModFunc[*dialect.DeleteQuery](func(q *dialect.DeleteQuery) {
		q.AppendHooks(func(ctx context.Context, exec bob.Executor) (context.Context, error) {
			return ReviewTaskPools.BeforeDeleteHooks.RunHooks(ctx, exec, o)
		})

		q.AppendLoader(bob.LoaderFunc(func(ctx context.Context, exec bob.Executor, retrieved any) error {
			var err error
			switch retrieved := retrieved.(type) {
			case *ReviewTaskPool:
				o.copyMatchingRows(retrieved)
			case []*ReviewTaskPool:
				o.copyMatchingRows(retrieved...)
			case ReviewTaskPoolSlice:
				o.copyMatchingRows(retrieved...)
			default:
				// If the retrieved value is not a ReviewTaskPool or a slice of ReviewTaskPool
				// then run the AfterDeleteHooks on the slice
				_, err = ReviewTaskPools.AfterDeleteHooks.RunHooks(ctx, exec, o)
			}

			return err
		}))

		q.AppendWhere(o.pkIN())
	})
}

func (o ReviewTaskPoolSlice) UpdateAll(ctx context.Context, exec bob.Executor, vals ReviewTaskPoolSetter) error {
	if len(o) == 0 {
		return nil
	}

	_, err := ReviewTaskPools.Update(vals.UpdateMod(), o.UpdateMod()).All(ctx, exec)
	return err
}

func (o ReviewTaskPoolSlice) DeleteAll(ctx context.Context, exec bob.Executor) error {
	if len(o) == 0 {
		return nil
	}

	_, err := ReviewTaskPools.Delete(o.DeleteMod()).Exec(ctx, exec)
	return err
}

func (o ReviewTaskPoolSlice) ReloadAll(ctx context.Context, exec bob.Executor) error {
	if len(o) == 0 {
		return nil
	}

	o2, err := ReviewTaskPools.Query(sm.Where(o.pkIN())).All(ctx, exec)
	if err != nil {
		return err
	}

	o.copyMatchingRows(o2...)

	return nil
}

// FeaturePool starts a query for related objects on feature_pool
func (o *ReviewTaskPool) FeaturePool(mods ...bob.Mod[*dialect.SelectQuery]) FeaturePoolsQuery {
	return FeaturePools.Query(append(mods,
		sm.Where(FeaturePools.Columns.FeatureID.EQ(psql.Arg(o.FeaturePoolID))),
	)...)
}

func (os ReviewTaskPoolSlice) FeaturePool(mods ...bob.Mod[*dialect.SelectQuery]) FeaturePoolsQuery {
	pkFeaturePoolID := make(pgtypes.Array[int32], 0, len(os))
	for _, o := range os {
		if o == nil {
			continue
		}
		pkFeaturePoolID = append(pkFeaturePoolID, o.FeaturePoolID)
	}
	PKArgExpr := psql.Select(sm.Columns(
		psql.F("unnest", psql.Cast(psql.Arg(pkFeaturePoolID), "integer[]")),
	))

	return FeaturePools.Query(append(mods,
		sm.Where(psql.Group(FeaturePools.Columns.FeatureID).OP("IN", PKArgExpr)),
	)...)
}

// ReviewTask starts a query for related objects on review_task
func (o *ReviewTaskPool) ReviewTask(mods ...bob.Mod[*dialect.SelectQuery]) ReviewTasksQuery {
	return ReviewTasks.Query(append(mods,
		sm.Where(ReviewTasks.Columns.ID.EQ(psql.Arg(o.ReviewTaskID))),
	)...)
}

func (os ReviewTaskPoolSlice) ReviewTask(mods ...bob.Mod[*dialect.SelectQuery]) ReviewTasksQuery {
	pkReviewTaskID := make(pgtypes.Array[int32], 0, len(os))
	for _, o := range os {
		if o == nil {
			continue
		}
		pkReviewTaskID = append(pkReviewTaskID, o.ReviewTaskID)
	}
	PKArgExpr := psql.Select(sm.Columns(
		psql.F("unnest", psql.Cast(psql.Arg(pkReviewTaskID), "integer[]")),
	))

	return ReviewTasks.Query(append(mods,
		sm.Where(psql.Group(ReviewTasks.Columns.ID).OP("IN", PKArgExpr)),
	)...)
}

func attachReviewTaskPoolFeaturePool0(ctx context.Context, exec bob.Executor, count int, reviewTaskPool0 *ReviewTaskPool, featurePool1 *FeaturePool) (*ReviewTaskPool, error) {
	setter := &ReviewTaskPoolSetter{
		FeaturePoolID: omit.From(featurePool1.FeatureID),
	}

	err := reviewTaskPool0.Update(ctx, exec, setter)
	if err != nil {
		return nil, fmt.Errorf("attachReviewTaskPoolFeaturePool0: %w", err)
	}

	return reviewTaskPool0, nil
}

func (reviewTaskPool0 *ReviewTaskPool) InsertFeaturePool(ctx context.Context, exec bob.Executor, related *FeaturePoolSetter) error {
	var err error

	featurePool1, err := FeaturePools.Insert(related).One(ctx, exec)
	if err != nil {
		return fmt.Errorf("inserting related objects: %w", err)
	}

	_, err = attachReviewTaskPoolFeaturePool0(ctx, exec, 1, reviewTaskPool0, featurePool1)
	if err != nil {
		return err
	}

	reviewTaskPool0.R.FeaturePool = featurePool1

	featurePool1.R.ReviewTaskPools = append(featurePool1.R.ReviewTaskPools, reviewTaskPool0)

	return nil
}

func (reviewTaskPool0 *ReviewTaskPool) AttachFeaturePool(ctx context.Context, exec bob.Executor, featurePool1 *FeaturePool) error {
	var err error

	_, err = attachReviewTaskPoolFeaturePool0(ctx, exec, 1, reviewTaskPool0, featurePool1)
	if err != nil {
		return err
	}

	reviewTaskPool0.R.FeaturePool = featurePool1

	featurePool1.R.ReviewTaskPools = append(featurePool1.R.ReviewTaskPools, reviewTaskPool0)

	return nil
}

func attachReviewTaskPoolReviewTask0(ctx context.Context, exec bob.Executor, count int, reviewTaskPool0 *ReviewTaskPool, reviewTask1 *ReviewTask) (*ReviewTaskPool, error) {
	setter := &ReviewTaskPoolSetter{
		ReviewTaskID: omit.From(reviewTask1.ID),
	}

	err := reviewTaskPool0.Update(ctx, exec, setter)
	if err != nil {
		return nil, fmt.Errorf("attachReviewTaskPoolReviewTask0: %w", err)
	}

	return reviewTaskPool0, nil
}

func (reviewTaskPool0 *ReviewTaskPool) InsertReviewTask(ctx context.Context, exec bob.Executor, related *ReviewTaskSetter) error {
	var err error

	reviewTask1, err := ReviewTasks.Insert(related).One(ctx, exec)
	if err != nil {
		return fmt.Errorf("inserting related objects: %w", err)
	}

	_, err = attachReviewTaskPoolReviewTask0(ctx, exec, 1, reviewTaskPool0, reviewTask1)
	if err != nil {
		return err
	}

	reviewTaskPool0.R.ReviewTask = reviewTask1

	reviewTask1.R.ReviewTaskPool = reviewTaskPool0

	return nil
}

func (reviewTaskPool0 *ReviewTaskPool) AttachReviewTask(ctx context.Context, exec bob.Executor, reviewTask1 *ReviewTask) error {
	var err error

	_, err = attachReviewTaskPoolReviewTask0(ctx, exec, 1, reviewTaskPool0, reviewTask1)
	if err != nil {
		return err
	}

	reviewTaskPool0.R.ReviewTask = reviewTask1

	reviewTask1.R.ReviewTaskPool = reviewTaskPool0

	return nil
}

type reviewTaskPoolWhere[Q psql.Filterable] struct {
	FeaturePoolID psql.WhereMod[Q, int32]
	Location      psql.WhereNullMod[Q, string]
	Geometry      psql.WhereNullMod[Q, string]
	ReviewTaskID  psql.WhereMod[Q, int32]
	Condition     psql.WhereNullMod[Q, enums.Poolconditiontype]
}

func (reviewTaskPoolWhere[Q]) AliasedAs(alias string) reviewTaskPoolWhere[Q] {
	return buildReviewTaskPoolWhere[Q](buildReviewTaskPoolColumns(alias))
}

func buildReviewTaskPoolWhere[Q psql.Filterable](cols reviewTaskPoolColumns) reviewTaskPoolWhere[Q] {
	return reviewTaskPoolWhere[Q]{
		FeaturePoolID: psql.Where[Q, int32](cols.FeaturePoolID),
		Location:      psql.WhereNull[Q, string](cols.Location),
		Geometry:      psql.WhereNull[Q, string](cols.Geometry),
		ReviewTaskID:  psql.Where[Q, int32](cols.ReviewTaskID),
		Condition:     psql.WhereNull[Q, enums.Poolconditiontype](cols.Condition),
	}
}

func (o *ReviewTaskPool) Preload(name string, retrieved any) error {
	if o == nil {
		return nil
	}

	switch name {
	case "FeaturePool":
		rel, ok := retrieved.(*FeaturePool)
		if !ok {
			return fmt.Errorf("reviewTaskPool cannot load %T as %q", retrieved, name)
		}

		o.R.FeaturePool = rel

		if rel != nil {
			rel.R.ReviewTaskPools = ReviewTaskPoolSlice{o}
		}
		return nil
	case "ReviewTask":
		rel, ok := retrieved.(*ReviewTask)
		if !ok {
			return fmt.Errorf("reviewTaskPool cannot load %T as %q", retrieved, name)
		}

		o.R.ReviewTask = rel

		if rel != nil {
			rel.R.ReviewTaskPool = o
		}
		return nil
	default:
		return fmt.Errorf("reviewTaskPool has no relationship %q", name)
	}
}

type reviewTaskPoolPreloader struct {
	FeaturePool func(...psql.PreloadOption) psql.Preloader
	ReviewTask  func(...psql.PreloadOption) psql.Preloader
}

func buildReviewTaskPoolPreloader() reviewTaskPoolPreloader {
	return reviewTaskPoolPreloader{
		FeaturePool: func(opts ...psql.PreloadOption) psql.Preloader {
			return psql.Preload[*FeaturePool, FeaturePoolSlice](psql.PreloadRel{
				Name: "FeaturePool",
				Sides: []psql.PreloadSide{
					{
						From:        ReviewTaskPools,
						To:          FeaturePools,
						FromColumns: []string{"feature_pool_id"},
						ToColumns:   []string{"feature_id"},
					},
				},
			}, FeaturePools.Columns.Names(), opts...)
		},
		ReviewTask: func(opts ...psql.PreloadOption) psql.Preloader {
			return psql.Preload[*ReviewTask, ReviewTaskSlice](psql.PreloadRel{
				Name: "ReviewTask",
				Sides: []psql.PreloadSide{
					{
						From:        ReviewTaskPools,
						To:          ReviewTasks,
						FromColumns: []string{"review_task_id"},
						ToColumns:   []string{"id"},
					},
				},
			}, ReviewTasks.Columns.Names(), opts...)
		},
	}
}

type reviewTaskPoolThenLoader[Q orm.Loadable] struct {
	FeaturePool func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q]
	ReviewTask  func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q]
}

func buildReviewTaskPoolThenLoader[Q orm.Loadable]() reviewTaskPoolThenLoader[Q] {
	type FeaturePoolLoadInterface interface {
		LoadFeaturePool(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error
	}
	type ReviewTaskLoadInterface interface {
		LoadReviewTask(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error
	}

	return reviewTaskPoolThenLoader[Q]{
		FeaturePool: thenLoadBuilder[Q](
			"FeaturePool",
			func(ctx context.Context, exec bob.Executor, retrieved FeaturePoolLoadInterface, mods ...bob.Mod[*dialect.SelectQuery]) error {
				return retrieved.LoadFeaturePool(ctx, exec, mods...)
			},
		),
		ReviewTask: thenLoadBuilder[Q](
			"ReviewTask",
			func(ctx context.Context, exec bob.Executor, retrieved ReviewTaskLoadInterface, mods ...bob.Mod[*dialect.SelectQuery]) error {
				return retrieved.LoadReviewTask(ctx, exec, mods...)
			},
		),
	}
}

// LoadFeaturePool loads the reviewTaskPool's FeaturePool into the .R struct
func (o *ReviewTaskPool) LoadFeaturePool(ctx context.Context, exec bob.Executor, mods ...bob.Mod[*dialect.SelectQuery]) error {
	if o == nil {
		return nil
	}

	// Reset the relationship
	o.R.FeaturePool = nil

	related, err := o.FeaturePool(mods...).One(ctx, exec)
	if err != nil {
		return err
	}

	related.R.ReviewTaskPools = ReviewTaskPoolSlice{o}

	o.R.FeaturePool = related
	return nil
}

// LoadFeaturePool loads the reviewTaskPool's FeaturePool into the .R struct
func (os ReviewTaskPoolSlice) LoadFeaturePool(ctx context.Context, exec bob.Executor, mods ...bob.Mod[*dialect.SelectQuery]) error {
	if len(os) == 0 {
		return nil
	}

	featurePools, err := os.FeaturePool(mods...).All(ctx, exec)
	if err != nil {
		return err
	}

	for _, o := range os {
		if o == nil {
			continue
		}

		for _, rel := range featurePools {

			if !(o.FeaturePoolID == rel.FeatureID) {
				continue
			}

			rel.R.ReviewTaskPools = append(rel.R.ReviewTaskPools, o)

			o.R.FeaturePool = rel
			break
		}
	}

	return nil
}

// LoadReviewTask loads the reviewTaskPool's ReviewTask into the .R struct
func (o *ReviewTaskPool) LoadReviewTask(ctx context.Context, exec bob.Executor, mods ...bob.Mod[*dialect.SelectQuery]) error {
	if o == nil {
		return nil
	}

	// Reset the relationship
	o.R.ReviewTask = nil

	related, err := o.ReviewTask(mods...).One(ctx, exec)
	if err != nil {
		return err
	}

	related.R.ReviewTaskPool = o

	o.R.ReviewTask = related
	return nil
}

// LoadReviewTask loads the reviewTaskPool's ReviewTask into the .R struct
func (os ReviewTaskPoolSlice) LoadReviewTask(ctx context.Context, exec bob.Executor, mods ...bob.Mod[*dialect.SelectQuery]) error {
	if len(os) == 0 {
		return nil
	}

	reviewTasks, err := os.ReviewTask(mods...).All(ctx, exec)
	if err != nil {
		return err
	}

	for _, o := range os {
		if o == nil {
			continue
		}

		for _, rel := range reviewTasks {

			if !(o.ReviewTaskID == rel.ID) {
				continue
			}

			rel.R.ReviewTaskPool = o

			o.R.ReviewTask = rel
			break
		}
	}

	return nil
}
