// 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"
)

// AuthGroup is an object representing the database table.
type AuthGroup struct {
	ID   int32  `db:"id,pk,autoincr" `
	Name string `db:"name" `

	R authGroupR `db:"-" `
}

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

// AuthGroups contains methods to work with the auth_group table
var AuthGroups = mysql.NewTablex[*AuthGroup, AuthGroupSlice, *AuthGroupSetter]("auth_group", buildAuthGroupColumns("auth_group"), []string{"id"}, []string{"name"})

// AuthGroupsQuery is a query on the auth_group table
type AuthGroupsQuery = *mysql.ViewQuery[*AuthGroup, AuthGroupSlice]

// authGroupR is where relationships are stored.
type authGroupR struct {
	GroupAuthGroupPermissions AuthGroupPermissionSlice // auth_group_permissions_group_id_b120cbf9_fk_auth_group_id
	GroupAuthUserGroups       AuthUserGroupSlice       // auth_user_groups_group_id_97559544_fk_auth_group_id
}

func buildAuthGroupColumns(alias string) authGroupColumns {
	return authGroupColumns{
		ColumnsExpr: expr.NewColumnsExpr(
			"id", "name",
		).WithParent("auth_group"),
		tableAlias: alias,
		ID:         mysql.Quote(alias, "id"),
		Name:       mysql.Quote(alias, "name"),
	}
}

type authGroupColumns struct {
	expr.ColumnsExpr
	tableAlias string
	ID         mysql.Expression
	Name       mysql.Expression
}

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

func (authGroupColumns) AliasedAs(alias string) authGroupColumns {
	return buildAuthGroupColumns(alias)
}

// AuthGroupSetter is used for insert/upsert/update operations
// All values are optional, and do not have to be set
// Generated columns are not included
type AuthGroupSetter struct {
	ID   omit.Val[int32]  `db:"id,pk,autoincr" `
	Name omit.Val[string] `db:"name" `
}

func (s AuthGroupSetter) SetColumns() []string {
	vals := make([]string, 0, 2)
	if s.ID.IsValue() {
		vals = append(vals, "id")
	}
	if s.Name.IsValue() {
		vals = append(vals, "name")
	}
	return vals
}

func (s AuthGroupSetter) Overwrite(t *AuthGroup) {
	if s.ID.IsValue() {
		t.ID = s.ID.MustGet()
	}
	if s.Name.IsValue() {
		t.Name = s.Name.MustGet()
	}
}

func (s *AuthGroupSetter) Apply(q *dialect.InsertQuery) {
	q.AppendHooks(func(ctx context.Context, exec bob.Executor) (context.Context, error) {
		return AuthGroups.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.Name.IsValue()) {
				return mysql.Raw("DEFAULT").WriteSQL(ctx, w, d, start)
			}
			return mysql.Arg(s.Name.MustGet()).WriteSQL(ctx, w, d, start)
		}))
}

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

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

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

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

	return exprs
}

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

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

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

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

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

	return err
}

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

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

	s.Overwrite(o)

	return nil
}

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

// Reload refreshes the AuthGroup using the executor
func (o *AuthGroup) Reload(ctx context.Context, exec bob.Executor) error {
	o2, err := AuthGroups.Query(
		sm.Where(AuthGroups.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 AuthGroupSlice is retrieved from the database
func (o AuthGroupSlice) AfterQueryHook(ctx context.Context, exec bob.Executor, queryType bob.QueryType) error {
	var err error

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

	return err
}

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

	return mysql.Quote("auth_group", "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 AuthGroupSlice) copyMatchingRows(from ...*AuthGroup) {
	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 AuthGroupSlice) 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 AuthGroups.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 *AuthGroup:
				o.copyMatchingRows(retrieved)
			case []*AuthGroup:
				o.copyMatchingRows(retrieved...)
			case AuthGroupSlice:
				o.copyMatchingRows(retrieved...)
			default:
				// If the retrieved value is not a AuthGroup or a slice of AuthGroup
				// then run the AfterUpdateHooks on the slice
				_, err = AuthGroups.AfterUpdateHooks.RunHooks(ctx, exec, o)
			}

			return err
		}))

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

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

			return err
		}))

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

func (o AuthGroupSlice) UpdateAll(ctx context.Context, exec bob.Executor, vals AuthGroupSetter) error {
	_, err := AuthGroups.Update(vals.UpdateMod(), o.UpdateMod()).Exec(ctx, exec)

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

	return err
}

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

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

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

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

	o.copyMatchingRows(o2...)

	return nil
}

// GroupAuthGroupPermissions starts a query for related objects on auth_group_permissions
func (o *AuthGroup) GroupAuthGroupPermissions(mods ...bob.Mod[*dialect.SelectQuery]) AuthGroupPermissionsQuery {
	return AuthGroupPermissions.Query(append(mods,
		sm.Where(AuthGroupPermissions.Columns.GroupID.EQ(mysql.Arg(o.ID))),
	)...)
}

func (os AuthGroupSlice) GroupAuthGroupPermissions(mods ...bob.Mod[*dialect.SelectQuery]) AuthGroupPermissionsQuery {
	PKArgSlice := make([]bob.Expression, len(os))
	for i, o := range os {
		PKArgSlice[i] = mysql.ArgGroup(o.ID)
	}
	PKArgExpr := mysql.Group(PKArgSlice...)

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

// GroupAuthUserGroups starts a query for related objects on auth_user_groups
func (o *AuthGroup) GroupAuthUserGroups(mods ...bob.Mod[*dialect.SelectQuery]) AuthUserGroupsQuery {
	return AuthUserGroups.Query(append(mods,
		sm.Where(AuthUserGroups.Columns.GroupID.EQ(mysql.Arg(o.ID))),
	)...)
}

func (os AuthGroupSlice) GroupAuthUserGroups(mods ...bob.Mod[*dialect.SelectQuery]) AuthUserGroupsQuery {
	PKArgSlice := make([]bob.Expression, len(os))
	for i, o := range os {
		PKArgSlice[i] = mysql.ArgGroup(o.ID)
	}
	PKArgExpr := mysql.Group(PKArgSlice...)

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

func insertAuthGroupGroupAuthGroupPermissions0(ctx context.Context, exec bob.Executor, authGroupPermissions1 []*AuthGroupPermissionSetter, authGroup0 *AuthGroup) (AuthGroupPermissionSlice, error) {
	for i := range authGroupPermissions1 {
		authGroupPermissions1[i].GroupID = omit.From(authGroup0.ID)
	}

	ret, err := AuthGroupPermissions.Insert(bob.ToMods(authGroupPermissions1...)).All(ctx, exec)
	if err != nil {
		return ret, fmt.Errorf("insertAuthGroupGroupAuthGroupPermissions0: %w", err)
	}

	return ret, nil
}

func attachAuthGroupGroupAuthGroupPermissions0(ctx context.Context, exec bob.Executor, count int, authGroupPermissions1 AuthGroupPermissionSlice, authGroup0 *AuthGroup) (AuthGroupPermissionSlice, error) {
	setter := &AuthGroupPermissionSetter{
		GroupID: omit.From(authGroup0.ID),
	}

	err := authGroupPermissions1.UpdateAll(ctx, exec, *setter)
	if err != nil {
		return nil, fmt.Errorf("attachAuthGroupGroupAuthGroupPermissions0: %w", err)
	}

	return authGroupPermissions1, nil
}

func (authGroup0 *AuthGroup) InsertGroupAuthGroupPermissions(ctx context.Context, exec bob.Executor, related ...*AuthGroupPermissionSetter) error {
	if len(related) == 0 {
		return nil
	}

	var err error

	authGroupPermissions1, err := insertAuthGroupGroupAuthGroupPermissions0(ctx, exec, related, authGroup0)
	if err != nil {
		return err
	}

	authGroup0.R.GroupAuthGroupPermissions = append(authGroup0.R.GroupAuthGroupPermissions, authGroupPermissions1...)

	for _, rel := range authGroupPermissions1 {
		rel.R.GroupAuthGroup = authGroup0
	}
	return nil
}

func (authGroup0 *AuthGroup) AttachGroupAuthGroupPermissions(ctx context.Context, exec bob.Executor, related ...*AuthGroupPermission) error {
	if len(related) == 0 {
		return nil
	}

	var err error
	authGroupPermissions1 := AuthGroupPermissionSlice(related)

	_, err = attachAuthGroupGroupAuthGroupPermissions0(ctx, exec, len(related), authGroupPermissions1, authGroup0)
	if err != nil {
		return err
	}

	authGroup0.R.GroupAuthGroupPermissions = append(authGroup0.R.GroupAuthGroupPermissions, authGroupPermissions1...)

	for _, rel := range related {
		rel.R.GroupAuthGroup = authGroup0
	}

	return nil
}

func insertAuthGroupGroupAuthUserGroups0(ctx context.Context, exec bob.Executor, authUserGroups1 []*AuthUserGroupSetter, authGroup0 *AuthGroup) (AuthUserGroupSlice, error) {
	for i := range authUserGroups1 {
		authUserGroups1[i].GroupID = omit.From(authGroup0.ID)
	}

	ret, err := AuthUserGroups.Insert(bob.ToMods(authUserGroups1...)).All(ctx, exec)
	if err != nil {
		return ret, fmt.Errorf("insertAuthGroupGroupAuthUserGroups0: %w", err)
	}

	return ret, nil
}

func attachAuthGroupGroupAuthUserGroups0(ctx context.Context, exec bob.Executor, count int, authUserGroups1 AuthUserGroupSlice, authGroup0 *AuthGroup) (AuthUserGroupSlice, error) {
	setter := &AuthUserGroupSetter{
		GroupID: omit.From(authGroup0.ID),
	}

	err := authUserGroups1.UpdateAll(ctx, exec, *setter)
	if err != nil {
		return nil, fmt.Errorf("attachAuthGroupGroupAuthUserGroups0: %w", err)
	}

	return authUserGroups1, nil
}

func (authGroup0 *AuthGroup) InsertGroupAuthUserGroups(ctx context.Context, exec bob.Executor, related ...*AuthUserGroupSetter) error {
	if len(related) == 0 {
		return nil
	}

	var err error

	authUserGroups1, err := insertAuthGroupGroupAuthUserGroups0(ctx, exec, related, authGroup0)
	if err != nil {
		return err
	}

	authGroup0.R.GroupAuthUserGroups = append(authGroup0.R.GroupAuthUserGroups, authUserGroups1...)

	for _, rel := range authUserGroups1 {
		rel.R.GroupAuthGroup = authGroup0
	}
	return nil
}

func (authGroup0 *AuthGroup) AttachGroupAuthUserGroups(ctx context.Context, exec bob.Executor, related ...*AuthUserGroup) error {
	if len(related) == 0 {
		return nil
	}

	var err error
	authUserGroups1 := AuthUserGroupSlice(related)

	_, err = attachAuthGroupGroupAuthUserGroups0(ctx, exec, len(related), authUserGroups1, authGroup0)
	if err != nil {
		return err
	}

	authGroup0.R.GroupAuthUserGroups = append(authGroup0.R.GroupAuthUserGroups, authUserGroups1...)

	for _, rel := range related {
		rel.R.GroupAuthGroup = authGroup0
	}

	return nil
}

type authGroupWhere[Q mysql.Filterable] struct {
	ID   mysql.WhereMod[Q, int32]
	Name mysql.WhereMod[Q, string]
}

func (authGroupWhere[Q]) AliasedAs(alias string) authGroupWhere[Q] {
	return buildAuthGroupWhere[Q](buildAuthGroupColumns(alias))
}

func buildAuthGroupWhere[Q mysql.Filterable](cols authGroupColumns) authGroupWhere[Q] {
	return authGroupWhere[Q]{
		ID:   mysql.Where[Q, int32](cols.ID),
		Name: mysql.Where[Q, string](cols.Name),
	}
}

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

	switch name {
	case "GroupAuthGroupPermissions":
		rels, ok := retrieved.(AuthGroupPermissionSlice)
		if !ok {
			return fmt.Errorf("authGroup cannot load %T as %q", retrieved, name)
		}

		o.R.GroupAuthGroupPermissions = rels

		for _, rel := range rels {
			if rel != nil {
				rel.R.GroupAuthGroup = o
			}
		}
		return nil
	case "GroupAuthUserGroups":
		rels, ok := retrieved.(AuthUserGroupSlice)
		if !ok {
			return fmt.Errorf("authGroup cannot load %T as %q", retrieved, name)
		}

		o.R.GroupAuthUserGroups = rels

		for _, rel := range rels {
			if rel != nil {
				rel.R.GroupAuthGroup = o
			}
		}
		return nil
	default:
		return fmt.Errorf("authGroup has no relationship %q", name)
	}
}

type authGroupPreloader struct{}

func buildAuthGroupPreloader() authGroupPreloader {
	return authGroupPreloader{}
}

type authGroupThenLoader[Q orm.Loadable] struct {
	GroupAuthGroupPermissions func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q]
	GroupAuthUserGroups       func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q]
}

func buildAuthGroupThenLoader[Q orm.Loadable]() authGroupThenLoader[Q] {
	type GroupAuthGroupPermissionsLoadInterface interface {
		LoadGroupAuthGroupPermissions(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error
	}
	type GroupAuthUserGroupsLoadInterface interface {
		LoadGroupAuthUserGroups(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error
	}

	return authGroupThenLoader[Q]{
		GroupAuthGroupPermissions: thenLoadBuilder[Q](
			"GroupAuthGroupPermissions",
			func(ctx context.Context, exec bob.Executor, retrieved GroupAuthGroupPermissionsLoadInterface, mods ...bob.Mod[*dialect.SelectQuery]) error {
				return retrieved.LoadGroupAuthGroupPermissions(ctx, exec, mods...)
			},
		),
		GroupAuthUserGroups: thenLoadBuilder[Q](
			"GroupAuthUserGroups",
			func(ctx context.Context, exec bob.Executor, retrieved GroupAuthUserGroupsLoadInterface, mods ...bob.Mod[*dialect.SelectQuery]) error {
				return retrieved.LoadGroupAuthUserGroups(ctx, exec, mods...)
			},
		),
	}
}

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

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

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

	for _, rel := range related {
		rel.R.GroupAuthGroup = o
	}

	o.R.GroupAuthGroupPermissions = related
	return nil
}

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

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

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

		o.R.GroupAuthGroupPermissions = nil
	}

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

		for _, rel := range authGroupPermissions {

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

			rel.R.GroupAuthGroup = o

			o.R.GroupAuthGroupPermissions = append(o.R.GroupAuthGroupPermissions, rel)
		}
	}

	return nil
}

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

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

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

	for _, rel := range related {
		rel.R.GroupAuthGroup = o
	}

	o.R.GroupAuthUserGroups = related
	return nil
}

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

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

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

		o.R.GroupAuthUserGroups = nil
	}

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

		for _, rel := range authUserGroups {

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

			rel.R.GroupAuthGroup = o

			o.R.GroupAuthUserGroups = append(o.R.GroupAuthUserGroups, rel)
		}
	}

	return nil
}

type authGroupJoins[Q dialect.Joinable] struct {
	typ                       string
	GroupAuthGroupPermissions modAs[Q, authGroupPermissionColumns]
	GroupAuthUserGroups       modAs[Q, authUserGroupColumns]
}

func (j authGroupJoins[Q]) aliasedAs(alias string) authGroupJoins[Q] {
	return buildAuthGroupJoins[Q](buildAuthGroupColumns(alias), j.typ)
}

func buildAuthGroupJoins[Q dialect.Joinable](cols authGroupColumns, typ string) authGroupJoins[Q] {
	return authGroupJoins[Q]{
		typ: typ,
		GroupAuthGroupPermissions: modAs[Q, authGroupPermissionColumns]{
			c: AuthGroupPermissions.Columns,
			f: func(to authGroupPermissionColumns) bob.Mod[Q] {
				mods := make(mods.QueryMods[Q], 0, 1)

				{
					mods = append(mods, dialect.Join[Q](typ, AuthGroupPermissions.Name().As(to.Alias())).On(
						to.GroupID.EQ(cols.ID),
					))
				}

				return mods
			},
		},
		GroupAuthUserGroups: modAs[Q, authUserGroupColumns]{
			c: AuthUserGroups.Columns,
			f: func(to authUserGroupColumns) bob.Mod[Q] {
				mods := make(mods.QueryMods[Q], 0, 1)

				{
					mods = append(mods, dialect.Join[Q](typ, AuthUserGroups.Name().As(to.Alias())).On(
						to.GroupID.EQ(cols.ID),
					))
				}

				return mods
			},
		},
	}
}
