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

// AuthGroupPermission is an object representing the database table.
type AuthGroupPermission struct {
	ID           int32 `db:"id,pk,autoincr" `
	GroupID      int32 `db:"group_id" `
	PermissionID int32 `db:"permission_id" `

	R authGroupPermissionR `db:"-" `
}

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

// AuthGroupPermissions contains methods to work with the auth_group_permissions table
var AuthGroupPermissions = mysql.NewTablex[*AuthGroupPermission, AuthGroupPermissionSlice, *AuthGroupPermissionSetter]("auth_group_permissions", buildAuthGroupPermissionColumns("auth_group_permissions"), []string{"id"}, []string{"group_id", "permission_id"})

// AuthGroupPermissionsQuery is a query on the auth_group_permissions table
type AuthGroupPermissionsQuery = *mysql.ViewQuery[*AuthGroupPermission, AuthGroupPermissionSlice]

// authGroupPermissionR is where relationships are stored.
type authGroupPermissionR struct {
	PermissionAuthPermission *AuthPermission // auth_group_permissio_permission_id_84c5c92e_fk_auth_perm
	GroupAuthGroup           *AuthGroup      // auth_group_permissions_group_id_b120cbf9_fk_auth_group_id
}

func buildAuthGroupPermissionColumns(alias string) authGroupPermissionColumns {
	return authGroupPermissionColumns{
		ColumnsExpr: expr.NewColumnsExpr(
			"id", "group_id", "permission_id",
		).WithParent("auth_group_permissions"),
		tableAlias:   alias,
		ID:           mysql.Quote(alias, "id"),
		GroupID:      mysql.Quote(alias, "group_id"),
		PermissionID: mysql.Quote(alias, "permission_id"),
	}
}

type authGroupPermissionColumns struct {
	expr.ColumnsExpr
	tableAlias   string
	ID           mysql.Expression
	GroupID      mysql.Expression
	PermissionID mysql.Expression
}

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

func (authGroupPermissionColumns) AliasedAs(alias string) authGroupPermissionColumns {
	return buildAuthGroupPermissionColumns(alias)
}

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

func (s AuthGroupPermissionSetter) SetColumns() []string {
	vals := make([]string, 0, 3)
	if s.ID.IsValue() {
		vals = append(vals, "id")
	}
	if s.GroupID.IsValue() {
		vals = append(vals, "group_id")
	}
	if s.PermissionID.IsValue() {
		vals = append(vals, "permission_id")
	}
	return vals
}

func (s AuthGroupPermissionSetter) Overwrite(t *AuthGroupPermission) {
	if s.ID.IsValue() {
		t.ID = s.ID.MustGet()
	}
	if s.GroupID.IsValue() {
		t.GroupID = s.GroupID.MustGet()
	}
	if s.PermissionID.IsValue() {
		t.PermissionID = s.PermissionID.MustGet()
	}
}

func (s *AuthGroupPermissionSetter) Apply(q *dialect.InsertQuery) {
	q.AppendHooks(func(ctx context.Context, exec bob.Executor) (context.Context, error) {
		return AuthGroupPermissions.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.GroupID.IsValue()) {
				return mysql.Raw("DEFAULT").WriteSQL(ctx, w, d, start)
			}
			return mysql.Arg(s.GroupID.MustGet()).WriteSQL(ctx, w, d, start)
		}), bob.ExpressionFunc(func(ctx context.Context, w io.StringWriter, d bob.Dialect, start int) ([]any, error) {
			if !(s.PermissionID.IsValue()) {
				return mysql.Raw("DEFAULT").WriteSQL(ctx, w, d, start)
			}
			return mysql.Arg(s.PermissionID.MustGet()).WriteSQL(ctx, w, d, start)
		}))
}

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

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

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

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

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

	return exprs
}

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

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

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

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

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

	return err
}

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

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

	s.Overwrite(o)

	return nil
}

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

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

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

	return err
}

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

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

			return err
		}))

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

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

			return err
		}))

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

func (o AuthGroupPermissionSlice) UpdateAll(ctx context.Context, exec bob.Executor, vals AuthGroupPermissionSetter) error {
	_, err := AuthGroupPermissions.Update(vals.UpdateMod(), o.UpdateMod()).Exec(ctx, exec)

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

	return err
}

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

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

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

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

	o.copyMatchingRows(o2...)

	return nil
}

// PermissionAuthPermission starts a query for related objects on auth_permission
func (o *AuthGroupPermission) PermissionAuthPermission(mods ...bob.Mod[*dialect.SelectQuery]) AuthPermissionsQuery {
	return AuthPermissions.Query(append(mods,
		sm.Where(AuthPermissions.Columns.ID.EQ(mysql.Arg(o.PermissionID))),
	)...)
}

func (os AuthGroupPermissionSlice) PermissionAuthPermission(mods ...bob.Mod[*dialect.SelectQuery]) AuthPermissionsQuery {
	PKArgSlice := make([]bob.Expression, len(os))
	for i, o := range os {
		PKArgSlice[i] = mysql.ArgGroup(o.PermissionID)
	}
	PKArgExpr := mysql.Group(PKArgSlice...)

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

// GroupAuthGroup starts a query for related objects on auth_group
func (o *AuthGroupPermission) GroupAuthGroup(mods ...bob.Mod[*dialect.SelectQuery]) AuthGroupsQuery {
	return AuthGroups.Query(append(mods,
		sm.Where(AuthGroups.Columns.ID.EQ(mysql.Arg(o.GroupID))),
	)...)
}

func (os AuthGroupPermissionSlice) GroupAuthGroup(mods ...bob.Mod[*dialect.SelectQuery]) AuthGroupsQuery {
	PKArgSlice := make([]bob.Expression, len(os))
	for i, o := range os {
		PKArgSlice[i] = mysql.ArgGroup(o.GroupID)
	}
	PKArgExpr := mysql.Group(PKArgSlice...)

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

func attachAuthGroupPermissionPermissionAuthPermission0(ctx context.Context, exec bob.Executor, count int, authGroupPermission0 *AuthGroupPermission, authPermission1 *AuthPermission) (*AuthGroupPermission, error) {
	setter := &AuthGroupPermissionSetter{
		PermissionID: omit.From(authPermission1.ID),
	}

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

	return authGroupPermission0, nil
}

func (authGroupPermission0 *AuthGroupPermission) InsertPermissionAuthPermission(ctx context.Context, exec bob.Executor, related *AuthPermissionSetter) error {
	var err error

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

	_, err = attachAuthGroupPermissionPermissionAuthPermission0(ctx, exec, 1, authGroupPermission0, authPermission1)
	if err != nil {
		return err
	}

	authGroupPermission0.R.PermissionAuthPermission = authPermission1

	authPermission1.R.PermissionAuthGroupPermissions = append(authPermission1.R.PermissionAuthGroupPermissions, authGroupPermission0)

	return nil
}

func (authGroupPermission0 *AuthGroupPermission) AttachPermissionAuthPermission(ctx context.Context, exec bob.Executor, authPermission1 *AuthPermission) error {
	var err error

	_, err = attachAuthGroupPermissionPermissionAuthPermission0(ctx, exec, 1, authGroupPermission0, authPermission1)
	if err != nil {
		return err
	}

	authGroupPermission0.R.PermissionAuthPermission = authPermission1

	authPermission1.R.PermissionAuthGroupPermissions = append(authPermission1.R.PermissionAuthGroupPermissions, authGroupPermission0)

	return nil
}

func attachAuthGroupPermissionGroupAuthGroup0(ctx context.Context, exec bob.Executor, count int, authGroupPermission0 *AuthGroupPermission, authGroup1 *AuthGroup) (*AuthGroupPermission, error) {
	setter := &AuthGroupPermissionSetter{
		GroupID: omit.From(authGroup1.ID),
	}

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

	return authGroupPermission0, nil
}

func (authGroupPermission0 *AuthGroupPermission) InsertGroupAuthGroup(ctx context.Context, exec bob.Executor, related *AuthGroupSetter) error {
	var err error

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

	_, err = attachAuthGroupPermissionGroupAuthGroup0(ctx, exec, 1, authGroupPermission0, authGroup1)
	if err != nil {
		return err
	}

	authGroupPermission0.R.GroupAuthGroup = authGroup1

	authGroup1.R.GroupAuthGroupPermissions = append(authGroup1.R.GroupAuthGroupPermissions, authGroupPermission0)

	return nil
}

func (authGroupPermission0 *AuthGroupPermission) AttachGroupAuthGroup(ctx context.Context, exec bob.Executor, authGroup1 *AuthGroup) error {
	var err error

	_, err = attachAuthGroupPermissionGroupAuthGroup0(ctx, exec, 1, authGroupPermission0, authGroup1)
	if err != nil {
		return err
	}

	authGroupPermission0.R.GroupAuthGroup = authGroup1

	authGroup1.R.GroupAuthGroupPermissions = append(authGroup1.R.GroupAuthGroupPermissions, authGroupPermission0)

	return nil
}

type authGroupPermissionWhere[Q mysql.Filterable] struct {
	ID           mysql.WhereMod[Q, int32]
	GroupID      mysql.WhereMod[Q, int32]
	PermissionID mysql.WhereMod[Q, int32]
}

func (authGroupPermissionWhere[Q]) AliasedAs(alias string) authGroupPermissionWhere[Q] {
	return buildAuthGroupPermissionWhere[Q](buildAuthGroupPermissionColumns(alias))
}

func buildAuthGroupPermissionWhere[Q mysql.Filterable](cols authGroupPermissionColumns) authGroupPermissionWhere[Q] {
	return authGroupPermissionWhere[Q]{
		ID:           mysql.Where[Q, int32](cols.ID),
		GroupID:      mysql.Where[Q, int32](cols.GroupID),
		PermissionID: mysql.Where[Q, int32](cols.PermissionID),
	}
}

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

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

		o.R.PermissionAuthPermission = rel

		if rel != nil {
			rel.R.PermissionAuthGroupPermissions = AuthGroupPermissionSlice{o}
		}
		return nil
	case "GroupAuthGroup":
		rel, ok := retrieved.(*AuthGroup)
		if !ok {
			return fmt.Errorf("authGroupPermission cannot load %T as %q", retrieved, name)
		}

		o.R.GroupAuthGroup = rel

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

type authGroupPermissionPreloader struct {
	PermissionAuthPermission func(...mysql.PreloadOption) mysql.Preloader
	GroupAuthGroup           func(...mysql.PreloadOption) mysql.Preloader
}

func buildAuthGroupPermissionPreloader() authGroupPermissionPreloader {
	return authGroupPermissionPreloader{
		PermissionAuthPermission: func(opts ...mysql.PreloadOption) mysql.Preloader {
			return mysql.Preload[*AuthPermission, AuthPermissionSlice](mysql.PreloadRel{
				Name: "PermissionAuthPermission",
				Sides: []mysql.PreloadSide{
					{
						From:        AuthGroupPermissions,
						To:          AuthPermissions,
						FromColumns: []string{"permission_id"},
						ToColumns:   []string{"id"},
					},
				},
			}, AuthPermissions.Columns.Names(), opts...)
		},
		GroupAuthGroup: func(opts ...mysql.PreloadOption) mysql.Preloader {
			return mysql.Preload[*AuthGroup, AuthGroupSlice](mysql.PreloadRel{
				Name: "GroupAuthGroup",
				Sides: []mysql.PreloadSide{
					{
						From:        AuthGroupPermissions,
						To:          AuthGroups,
						FromColumns: []string{"group_id"},
						ToColumns:   []string{"id"},
					},
				},
			}, AuthGroups.Columns.Names(), opts...)
		},
	}
}

type authGroupPermissionThenLoader[Q orm.Loadable] struct {
	PermissionAuthPermission func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q]
	GroupAuthGroup           func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q]
}

func buildAuthGroupPermissionThenLoader[Q orm.Loadable]() authGroupPermissionThenLoader[Q] {
	type PermissionAuthPermissionLoadInterface interface {
		LoadPermissionAuthPermission(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error
	}
	type GroupAuthGroupLoadInterface interface {
		LoadGroupAuthGroup(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error
	}

	return authGroupPermissionThenLoader[Q]{
		PermissionAuthPermission: thenLoadBuilder[Q](
			"PermissionAuthPermission",
			func(ctx context.Context, exec bob.Executor, retrieved PermissionAuthPermissionLoadInterface, mods ...bob.Mod[*dialect.SelectQuery]) error {
				return retrieved.LoadPermissionAuthPermission(ctx, exec, mods...)
			},
		),
		GroupAuthGroup: thenLoadBuilder[Q](
			"GroupAuthGroup",
			func(ctx context.Context, exec bob.Executor, retrieved GroupAuthGroupLoadInterface, mods ...bob.Mod[*dialect.SelectQuery]) error {
				return retrieved.LoadGroupAuthGroup(ctx, exec, mods...)
			},
		),
	}
}

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

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

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

	related.R.PermissionAuthGroupPermissions = AuthGroupPermissionSlice{o}

	o.R.PermissionAuthPermission = related
	return nil
}

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

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

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

		for _, rel := range authPermissions {

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

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

			o.R.PermissionAuthPermission = rel
			break
		}
	}

	return nil
}

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

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

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

	related.R.GroupAuthGroupPermissions = AuthGroupPermissionSlice{o}

	o.R.GroupAuthGroup = related
	return nil
}

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

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

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

		for _, rel := range authGroups {

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

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

			o.R.GroupAuthGroup = rel
			break
		}
	}

	return nil
}

type authGroupPermissionJoins[Q dialect.Joinable] struct {
	typ                      string
	PermissionAuthPermission modAs[Q, authPermissionColumns]
	GroupAuthGroup           modAs[Q, authGroupColumns]
}

func (j authGroupPermissionJoins[Q]) aliasedAs(alias string) authGroupPermissionJoins[Q] {
	return buildAuthGroupPermissionJoins[Q](buildAuthGroupPermissionColumns(alias), j.typ)
}

func buildAuthGroupPermissionJoins[Q dialect.Joinable](cols authGroupPermissionColumns, typ string) authGroupPermissionJoins[Q] {
	return authGroupPermissionJoins[Q]{
		typ: typ,
		PermissionAuthPermission: modAs[Q, authPermissionColumns]{
			c: AuthPermissions.Columns,
			f: func(to authPermissionColumns) bob.Mod[Q] {
				mods := make(mods.QueryMods[Q], 0, 1)

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

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

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

				return mods
			},
		},
	}
}
