// Code generated by BobGen mysql v0.42.0. 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/aarondl/opt/omit"
	"github.com/stephenafamo/bob"
	"github.com/stephenafamo/bob/dialect/mysql"
	"github.com/stephenafamo/bob/dialect/mysql/dialect"
	"github.com/stephenafamo/bob/dialect/mysql/dm"
	"github.com/stephenafamo/bob/dialect/mysql/sm"
	"github.com/stephenafamo/bob/dialect/mysql/um"
	"github.com/stephenafamo/bob/expr"
	"github.com/stephenafamo/bob/mods"
	"github.com/stephenafamo/bob/orm"
)

// LocationsDataverse is an object representing the database table.
type LocationsDataverse struct {
	ID              int32  `db:"id,pk,autoincr" `
	Host            string `db:"host" `
	APIKey          string `db:"api_key" `
	AgentName       string `db:"agent_name" `
	AgentType       string `db:"agent_type" `
	AgentIdentifier string `db:"agent_identifier" `
	SpaceID         string `db:"space_id" `

	R locationsDataverseR `db:"-" `
}

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

// LocationsDataverses contains methods to work with the locations_dataverse table
var LocationsDataverses = mysql.NewTablex[*LocationsDataverse, LocationsDataverseSlice, *LocationsDataverseSetter]("locations_dataverse", buildLocationsDataverseColumns("locations_dataverse"), []string{"id"}, []string{"space_id"})

// LocationsDataversesQuery is a query on the locations_dataverse table
type LocationsDataversesQuery = *mysql.ViewQuery[*LocationsDataverse, LocationsDataverseSlice]

// locationsDataverseR is where relationships are stored.
type locationsDataverseR struct {
	SpaceLocationsSpace *LocationsSpace // locations_dataverse_space_id_1b94d732_fk_locations_space_uuid
}

func buildLocationsDataverseColumns(alias string) locationsDataverseColumns {
	return locationsDataverseColumns{
		ColumnsExpr: expr.NewColumnsExpr(
			"id", "host", "api_key", "agent_name", "agent_type", "agent_identifier", "space_id",
		).WithParent("locations_dataverse"),
		tableAlias:      alias,
		ID:              mysql.Quote(alias, "id"),
		Host:            mysql.Quote(alias, "host"),
		APIKey:          mysql.Quote(alias, "api_key"),
		AgentName:       mysql.Quote(alias, "agent_name"),
		AgentType:       mysql.Quote(alias, "agent_type"),
		AgentIdentifier: mysql.Quote(alias, "agent_identifier"),
		SpaceID:         mysql.Quote(alias, "space_id"),
	}
}

type locationsDataverseColumns struct {
	expr.ColumnsExpr
	tableAlias      string
	ID              mysql.Expression
	Host            mysql.Expression
	APIKey          mysql.Expression
	AgentName       mysql.Expression
	AgentType       mysql.Expression
	AgentIdentifier mysql.Expression
	SpaceID         mysql.Expression
}

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

func (locationsDataverseColumns) AliasedAs(alias string) locationsDataverseColumns {
	return buildLocationsDataverseColumns(alias)
}

// LocationsDataverseSetter is used for insert/upsert/update operations
// All values are optional, and do not have to be set
// Generated columns are not included
type LocationsDataverseSetter struct {
	ID              omit.Val[int32]  `db:"id,pk,autoincr" `
	Host            omit.Val[string] `db:"host" `
	APIKey          omit.Val[string] `db:"api_key" `
	AgentName       omit.Val[string] `db:"agent_name" `
	AgentType       omit.Val[string] `db:"agent_type" `
	AgentIdentifier omit.Val[string] `db:"agent_identifier" `
	SpaceID         omit.Val[string] `db:"space_id" `
}

func (s LocationsDataverseSetter) SetColumns() []string {
	vals := make([]string, 0, 7)
	if s.ID.IsValue() {
		vals = append(vals, "id")
	}
	if s.Host.IsValue() {
		vals = append(vals, "host")
	}
	if s.APIKey.IsValue() {
		vals = append(vals, "api_key")
	}
	if s.AgentName.IsValue() {
		vals = append(vals, "agent_name")
	}
	if s.AgentType.IsValue() {
		vals = append(vals, "agent_type")
	}
	if s.AgentIdentifier.IsValue() {
		vals = append(vals, "agent_identifier")
	}
	if s.SpaceID.IsValue() {
		vals = append(vals, "space_id")
	}
	return vals
}

func (s LocationsDataverseSetter) Overwrite(t *LocationsDataverse) {
	if s.ID.IsValue() {
		t.ID = s.ID.MustGet()
	}
	if s.Host.IsValue() {
		t.Host = s.Host.MustGet()
	}
	if s.APIKey.IsValue() {
		t.APIKey = s.APIKey.MustGet()
	}
	if s.AgentName.IsValue() {
		t.AgentName = s.AgentName.MustGet()
	}
	if s.AgentType.IsValue() {
		t.AgentType = s.AgentType.MustGet()
	}
	if s.AgentIdentifier.IsValue() {
		t.AgentIdentifier = s.AgentIdentifier.MustGet()
	}
	if s.SpaceID.IsValue() {
		t.SpaceID = s.SpaceID.MustGet()
	}
}

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

	q.AppendValues(
		bob.ExpressionFunc(func(ctx context.Context, w io.StringWriter, d bob.Dialect, start int) ([]any, error) {
			if !(s.ID.IsValue()) {
				return mysql.Raw("DEFAULT").WriteSQL(ctx, w, d, start)
			}
			return mysql.Arg(s.ID.MustGet()).WriteSQL(ctx, w, d, start)
		}), bob.ExpressionFunc(func(ctx context.Context, w io.StringWriter, d bob.Dialect, start int) ([]any, error) {
			if !(s.Host.IsValue()) {
				return mysql.Raw("DEFAULT").WriteSQL(ctx, w, d, start)
			}
			return mysql.Arg(s.Host.MustGet()).WriteSQL(ctx, w, d, start)
		}), bob.ExpressionFunc(func(ctx context.Context, w io.StringWriter, d bob.Dialect, start int) ([]any, error) {
			if !(s.APIKey.IsValue()) {
				return mysql.Raw("DEFAULT").WriteSQL(ctx, w, d, start)
			}
			return mysql.Arg(s.APIKey.MustGet()).WriteSQL(ctx, w, d, start)
		}), bob.ExpressionFunc(func(ctx context.Context, w io.StringWriter, d bob.Dialect, start int) ([]any, error) {
			if !(s.AgentName.IsValue()) {
				return mysql.Raw("DEFAULT").WriteSQL(ctx, w, d, start)
			}
			return mysql.Arg(s.AgentName.MustGet()).WriteSQL(ctx, w, d, start)
		}), bob.ExpressionFunc(func(ctx context.Context, w io.StringWriter, d bob.Dialect, start int) ([]any, error) {
			if !(s.AgentType.IsValue()) {
				return mysql.Raw("DEFAULT").WriteSQL(ctx, w, d, start)
			}
			return mysql.Arg(s.AgentType.MustGet()).WriteSQL(ctx, w, d, start)
		}), bob.ExpressionFunc(func(ctx context.Context, w io.StringWriter, d bob.Dialect, start int) ([]any, error) {
			if !(s.AgentIdentifier.IsValue()) {
				return mysql.Raw("DEFAULT").WriteSQL(ctx, w, d, start)
			}
			return mysql.Arg(s.AgentIdentifier.MustGet()).WriteSQL(ctx, w, d, start)
		}), bob.ExpressionFunc(func(ctx context.Context, w io.StringWriter, d bob.Dialect, start int) ([]any, error) {
			if !(s.SpaceID.IsValue()) {
				return mysql.Raw("DEFAULT").WriteSQL(ctx, w, d, start)
			}
			return mysql.Arg(s.SpaceID.MustGet()).WriteSQL(ctx, w, d, start)
		}))
}

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

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

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

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

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

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

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

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

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

	return exprs
}

// FindLocationsDataverse retrieves a single record by primary key
// If cols is empty Find will return all columns.
func FindLocationsDataverse(ctx context.Context, exec bob.Executor, IDPK int32, cols ...string) (*LocationsDataverse, error) {
	if len(cols) == 0 {
		return LocationsDataverses.Query(
			sm.Where(LocationsDataverses.Columns.ID.EQ(mysql.Arg(IDPK))),
		).One(ctx, exec)
	}

	return LocationsDataverses.Query(
		sm.Where(LocationsDataverses.Columns.ID.EQ(mysql.Arg(IDPK))),
		sm.Columns(LocationsDataverses.Columns.Only(cols...)),
	).One(ctx, exec)
}

// LocationsDataverseExists checks the presence of a single record by primary key
func LocationsDataverseExists(ctx context.Context, exec bob.Executor, IDPK int32) (bool, error) {
	return LocationsDataverses.Query(
		sm.Where(LocationsDataverses.Columns.ID.EQ(mysql.Arg(IDPK))),
	).Exists(ctx, exec)
}

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

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

	return err
}

// primaryKeyVals returns the primary key values of the LocationsDataverse
func (o *LocationsDataverse) primaryKeyVals() bob.Expression {
	return mysql.Arg(o.ID)
}

func (o *LocationsDataverse) pkEQ() dialect.Expression {
	return mysql.Quote("locations_dataverse", "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 LocationsDataverse
func (o *LocationsDataverse) Update(ctx context.Context, exec bob.Executor, s *LocationsDataverseSetter) error {
	_, err := LocationsDataverses.Update(s.UpdateMod(), um.Where(o.pkEQ())).Exec(ctx, exec)
	if err != nil {
		return err
	}

	s.Overwrite(o)

	return nil
}

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

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

	return nil
}

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

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

	return err
}

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

	return mysql.Quote("locations_dataverse", "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 LocationsDataverseSlice) copyMatchingRows(from ...*LocationsDataverse) {
	for i, old := range o {
		for _, new := range from {
			if new.ID != old.ID {
				continue
			}
			new.R = old.R
			o[i] = new
			break
		}
	}
}

// UpdateMod modifies an update query with "WHERE primary_key IN (o...)"
func (o LocationsDataverseSlice) 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 LocationsDataverses.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 *LocationsDataverse:
				o.copyMatchingRows(retrieved)
			case []*LocationsDataverse:
				o.copyMatchingRows(retrieved...)
			case LocationsDataverseSlice:
				o.copyMatchingRows(retrieved...)
			default:
				// If the retrieved value is not a LocationsDataverse or a slice of LocationsDataverse
				// then run the AfterUpdateHooks on the slice
				_, err = LocationsDataverses.AfterUpdateHooks.RunHooks(ctx, exec, o)
			}

			return err
		}))

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

// DeleteMod modifies an delete query with "WHERE primary_key IN (o...)"
func (o LocationsDataverseSlice) 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 LocationsDataverses.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 *LocationsDataverse:
				o.copyMatchingRows(retrieved)
			case []*LocationsDataverse:
				o.copyMatchingRows(retrieved...)
			case LocationsDataverseSlice:
				o.copyMatchingRows(retrieved...)
			default:
				// If the retrieved value is not a LocationsDataverse or a slice of LocationsDataverse
				// then run the AfterDeleteHooks on the slice
				_, err = LocationsDataverses.AfterDeleteHooks.RunHooks(ctx, exec, o)
			}

			return err
		}))

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

func (o LocationsDataverseSlice) UpdateAll(ctx context.Context, exec bob.Executor, vals LocationsDataverseSetter) error {
	_, err := LocationsDataverses.Update(vals.UpdateMod(), o.UpdateMod()).Exec(ctx, exec)

	for i := range o {
		vals.Overwrite(o[i])
	}

	return err
}

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

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

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

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

	o.copyMatchingRows(o2...)

	return nil
}

// SpaceLocationsSpace starts a query for related objects on locations_space
func (o *LocationsDataverse) SpaceLocationsSpace(mods ...bob.Mod[*dialect.SelectQuery]) LocationsSpacesQuery {
	return LocationsSpaces.Query(append(mods,
		sm.Where(LocationsSpaces.Columns.UUID.EQ(mysql.Arg(o.SpaceID))),
	)...)
}

func (os LocationsDataverseSlice) SpaceLocationsSpace(mods ...bob.Mod[*dialect.SelectQuery]) LocationsSpacesQuery {
	PKArgSlice := make([]bob.Expression, len(os))
	for i, o := range os {
		PKArgSlice[i] = mysql.ArgGroup(o.SpaceID)
	}
	PKArgExpr := mysql.Group(PKArgSlice...)

	return LocationsSpaces.Query(append(mods,
		sm.Where(mysql.Group(LocationsSpaces.Columns.UUID).OP("IN", PKArgExpr)),
	)...)
}

func attachLocationsDataverseSpaceLocationsSpace0(ctx context.Context, exec bob.Executor, count int, locationsDataverse0 *LocationsDataverse, locationsSpace1 *LocationsSpace) (*LocationsDataverse, error) {
	setter := &LocationsDataverseSetter{
		SpaceID: omit.From(locationsSpace1.UUID),
	}

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

	return locationsDataverse0, nil
}

func (locationsDataverse0 *LocationsDataverse) InsertSpaceLocationsSpace(ctx context.Context, exec bob.Executor, related *LocationsSpaceSetter) error {
	var err error

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

	_, err = attachLocationsDataverseSpaceLocationsSpace0(ctx, exec, 1, locationsDataverse0, locationsSpace1)
	if err != nil {
		return err
	}

	locationsDataverse0.R.SpaceLocationsSpace = locationsSpace1

	locationsSpace1.R.SpaceLocationsDataverse = locationsDataverse0

	return nil
}

func (locationsDataverse0 *LocationsDataverse) AttachSpaceLocationsSpace(ctx context.Context, exec bob.Executor, locationsSpace1 *LocationsSpace) error {
	var err error

	_, err = attachLocationsDataverseSpaceLocationsSpace0(ctx, exec, 1, locationsDataverse0, locationsSpace1)
	if err != nil {
		return err
	}

	locationsDataverse0.R.SpaceLocationsSpace = locationsSpace1

	locationsSpace1.R.SpaceLocationsDataverse = locationsDataverse0

	return nil
}

type locationsDataverseWhere[Q mysql.Filterable] struct {
	ID              mysql.WhereMod[Q, int32]
	Host            mysql.WhereMod[Q, string]
	APIKey          mysql.WhereMod[Q, string]
	AgentName       mysql.WhereMod[Q, string]
	AgentType       mysql.WhereMod[Q, string]
	AgentIdentifier mysql.WhereMod[Q, string]
	SpaceID         mysql.WhereMod[Q, string]
}

func (locationsDataverseWhere[Q]) AliasedAs(alias string) locationsDataverseWhere[Q] {
	return buildLocationsDataverseWhere[Q](buildLocationsDataverseColumns(alias))
}

func buildLocationsDataverseWhere[Q mysql.Filterable](cols locationsDataverseColumns) locationsDataverseWhere[Q] {
	return locationsDataverseWhere[Q]{
		ID:              mysql.Where[Q, int32](cols.ID),
		Host:            mysql.Where[Q, string](cols.Host),
		APIKey:          mysql.Where[Q, string](cols.APIKey),
		AgentName:       mysql.Where[Q, string](cols.AgentName),
		AgentType:       mysql.Where[Q, string](cols.AgentType),
		AgentIdentifier: mysql.Where[Q, string](cols.AgentIdentifier),
		SpaceID:         mysql.Where[Q, string](cols.SpaceID),
	}
}

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

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

		o.R.SpaceLocationsSpace = rel

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

type locationsDataversePreloader struct {
	SpaceLocationsSpace func(...mysql.PreloadOption) mysql.Preloader
}

func buildLocationsDataversePreloader() locationsDataversePreloader {
	return locationsDataversePreloader{
		SpaceLocationsSpace: func(opts ...mysql.PreloadOption) mysql.Preloader {
			return mysql.Preload[*LocationsSpace, LocationsSpaceSlice](mysql.PreloadRel{
				Name: "SpaceLocationsSpace",
				Sides: []mysql.PreloadSide{
					{
						From:        LocationsDataverses,
						To:          LocationsSpaces,
						FromColumns: []string{"space_id"},
						ToColumns:   []string{"uuid"},
					},
				},
			}, LocationsSpaces.Columns.Names(), opts...)
		},
	}
}

type locationsDataverseThenLoader[Q orm.Loadable] struct {
	SpaceLocationsSpace func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q]
}

func buildLocationsDataverseThenLoader[Q orm.Loadable]() locationsDataverseThenLoader[Q] {
	type SpaceLocationsSpaceLoadInterface interface {
		LoadSpaceLocationsSpace(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error
	}

	return locationsDataverseThenLoader[Q]{
		SpaceLocationsSpace: thenLoadBuilder[Q](
			"SpaceLocationsSpace",
			func(ctx context.Context, exec bob.Executor, retrieved SpaceLocationsSpaceLoadInterface, mods ...bob.Mod[*dialect.SelectQuery]) error {
				return retrieved.LoadSpaceLocationsSpace(ctx, exec, mods...)
			},
		),
	}
}

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

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

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

	related.R.SpaceLocationsDataverse = o

	o.R.SpaceLocationsSpace = related
	return nil
}

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

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

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

		for _, rel := range locationsSpaces {

			if !(o.SpaceID == rel.UUID) {
				continue
			}

			rel.R.SpaceLocationsDataverse = o

			o.R.SpaceLocationsSpace = rel
			break
		}
	}

	return nil
}

type locationsDataverseJoins[Q dialect.Joinable] struct {
	typ                 string
	SpaceLocationsSpace modAs[Q, locationsSpaceColumns]
}

func (j locationsDataverseJoins[Q]) aliasedAs(alias string) locationsDataverseJoins[Q] {
	return buildLocationsDataverseJoins[Q](buildLocationsDataverseColumns(alias), j.typ)
}

func buildLocationsDataverseJoins[Q dialect.Joinable](cols locationsDataverseColumns, typ string) locationsDataverseJoins[Q] {
	return locationsDataverseJoins[Q]{
		typ: typ,
		SpaceLocationsSpace: modAs[Q, locationsSpaceColumns]{
			c: LocationsSpaces.Columns,
			f: func(to locationsSpaceColumns) bob.Mod[Q] {
				mods := make(mods.QueryMods[Q], 0, 1)

				{
					mods = append(mods, dialect.Join[Q](typ, LocationsSpaces.Name().As(to.Alias())).On(
						to.UUID.EQ(cols.SpaceID),
					))
				}

				return mods
			},
		},
	}
}
