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

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

	R authUserUserPermissionR `db:"-" `
}

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

// AuthUserUserPermissions contains methods to work with the auth_user_user_permissions table
var AuthUserUserPermissions = mysql.NewTablex[*AuthUserUserPermission, AuthUserUserPermissionSlice, *AuthUserUserPermissionSetter]("auth_user_user_permissions", buildAuthUserUserPermissionColumns("auth_user_user_permissions"), []string{"id"}, []string{"user_id", "permission_id"})

// AuthUserUserPermissionsQuery is a query on the auth_user_user_permissions table
type AuthUserUserPermissionsQuery = *mysql.ViewQuery[*AuthUserUserPermission, AuthUserUserPermissionSlice]

// authUserUserPermissionR is where relationships are stored.
type authUserUserPermissionR struct {
	PermissionAuthPermission *AuthPermission // auth_user_user_permi_permission_id_1fbb5f2c_fk_auth_perm
	UserAuthUser             *AuthUser       // auth_user_user_permissions_user_id_a95ead1b_fk_auth_user_id
}

func buildAuthUserUserPermissionColumns(alias string) authUserUserPermissionColumns {
	return authUserUserPermissionColumns{
		ColumnsExpr: expr.NewColumnsExpr(
			"id", "user_id", "permission_id",
		).WithParent("auth_user_user_permissions"),
		tableAlias:   alias,
		ID:           mysql.Quote(alias, "id"),
		UserID:       mysql.Quote(alias, "user_id"),
		PermissionID: mysql.Quote(alias, "permission_id"),
	}
}

type authUserUserPermissionColumns struct {
	expr.ColumnsExpr
	tableAlias   string
	ID           mysql.Expression
	UserID       mysql.Expression
	PermissionID mysql.Expression
}

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

func (authUserUserPermissionColumns) AliasedAs(alias string) authUserUserPermissionColumns {
	return buildAuthUserUserPermissionColumns(alias)
}

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

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

func (s AuthUserUserPermissionSetter) Overwrite(t *AuthUserUserPermission) {
	if s.ID.IsValue() {
		t.ID = s.ID.MustGet()
	}
	if s.UserID.IsValue() {
		t.UserID = s.UserID.MustGet()
	}
	if s.PermissionID.IsValue() {
		t.PermissionID = s.PermissionID.MustGet()
	}
}

func (s *AuthUserUserPermissionSetter) Apply(q *dialect.InsertQuery) {
	q.AppendHooks(func(ctx context.Context, exec bob.Executor) (context.Context, error) {
		return AuthUserUserPermissions.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.UserID.IsValue()) {
				return mysql.Raw("DEFAULT").WriteSQL(ctx, w, d, start)
			}
			return mysql.Arg(s.UserID.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 AuthUserUserPermissionSetter) UpdateMod() bob.Mod[*dialect.UpdateQuery] {
	return um.Set(s.Expressions("auth_user_user_permissions")...)
}

func (s AuthUserUserPermissionSetter) 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.UserID.IsValue() {
		exprs = append(exprs, expr.Join{Sep: " = ", Exprs: []bob.Expression{
			mysql.Quote(append(prefix, "user_id")...),
			mysql.Arg(s.UserID),
		}})
	}

	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
}

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

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

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

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

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

	return err
}

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

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

	s.Overwrite(o)

	return nil
}

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

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

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

	return err
}

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

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

			return err
		}))

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

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

			return err
		}))

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

func (o AuthUserUserPermissionSlice) UpdateAll(ctx context.Context, exec bob.Executor, vals AuthUserUserPermissionSetter) error {
	_, err := AuthUserUserPermissions.Update(vals.UpdateMod(), o.UpdateMod()).Exec(ctx, exec)

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

	return err
}

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

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

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

	o2, err := AuthUserUserPermissions.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 *AuthUserUserPermission) PermissionAuthPermission(mods ...bob.Mod[*dialect.SelectQuery]) AuthPermissionsQuery {
	return AuthPermissions.Query(append(mods,
		sm.Where(AuthPermissions.Columns.ID.EQ(mysql.Arg(o.PermissionID))),
	)...)
}

func (os AuthUserUserPermissionSlice) 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)),
	)...)
}

// UserAuthUser starts a query for related objects on auth_user
func (o *AuthUserUserPermission) UserAuthUser(mods ...bob.Mod[*dialect.SelectQuery]) AuthUsersQuery {
	return AuthUsers.Query(append(mods,
		sm.Where(AuthUsers.Columns.ID.EQ(mysql.Arg(o.UserID))),
	)...)
}

func (os AuthUserUserPermissionSlice) UserAuthUser(mods ...bob.Mod[*dialect.SelectQuery]) AuthUsersQuery {
	PKArgSlice := make([]bob.Expression, len(os))
	for i, o := range os {
		PKArgSlice[i] = mysql.ArgGroup(o.UserID)
	}
	PKArgExpr := mysql.Group(PKArgSlice...)

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

func attachAuthUserUserPermissionPermissionAuthPermission0(ctx context.Context, exec bob.Executor, count int, authUserUserPermission0 *AuthUserUserPermission, authPermission1 *AuthPermission) (*AuthUserUserPermission, error) {
	setter := &AuthUserUserPermissionSetter{
		PermissionID: omit.From(authPermission1.ID),
	}

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

	return authUserUserPermission0, nil
}

func (authUserUserPermission0 *AuthUserUserPermission) 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 = attachAuthUserUserPermissionPermissionAuthPermission0(ctx, exec, 1, authUserUserPermission0, authPermission1)
	if err != nil {
		return err
	}

	authUserUserPermission0.R.PermissionAuthPermission = authPermission1

	authPermission1.R.PermissionAuthUserUserPermissions = append(authPermission1.R.PermissionAuthUserUserPermissions, authUserUserPermission0)

	return nil
}

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

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

	authUserUserPermission0.R.PermissionAuthPermission = authPermission1

	authPermission1.R.PermissionAuthUserUserPermissions = append(authPermission1.R.PermissionAuthUserUserPermissions, authUserUserPermission0)

	return nil
}

func attachAuthUserUserPermissionUserAuthUser0(ctx context.Context, exec bob.Executor, count int, authUserUserPermission0 *AuthUserUserPermission, authUser1 *AuthUser) (*AuthUserUserPermission, error) {
	setter := &AuthUserUserPermissionSetter{
		UserID: omit.From(authUser1.ID),
	}

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

	return authUserUserPermission0, nil
}

func (authUserUserPermission0 *AuthUserUserPermission) InsertUserAuthUser(ctx context.Context, exec bob.Executor, related *AuthUserSetter) error {
	var err error

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

	_, err = attachAuthUserUserPermissionUserAuthUser0(ctx, exec, 1, authUserUserPermission0, authUser1)
	if err != nil {
		return err
	}

	authUserUserPermission0.R.UserAuthUser = authUser1

	authUser1.R.UserAuthUserUserPermissions = append(authUser1.R.UserAuthUserUserPermissions, authUserUserPermission0)

	return nil
}

func (authUserUserPermission0 *AuthUserUserPermission) AttachUserAuthUser(ctx context.Context, exec bob.Executor, authUser1 *AuthUser) error {
	var err error

	_, err = attachAuthUserUserPermissionUserAuthUser0(ctx, exec, 1, authUserUserPermission0, authUser1)
	if err != nil {
		return err
	}

	authUserUserPermission0.R.UserAuthUser = authUser1

	authUser1.R.UserAuthUserUserPermissions = append(authUser1.R.UserAuthUserUserPermissions, authUserUserPermission0)

	return nil
}

type authUserUserPermissionWhere[Q mysql.Filterable] struct {
	ID           mysql.WhereMod[Q, int32]
	UserID       mysql.WhereMod[Q, int32]
	PermissionID mysql.WhereMod[Q, int32]
}

func (authUserUserPermissionWhere[Q]) AliasedAs(alias string) authUserUserPermissionWhere[Q] {
	return buildAuthUserUserPermissionWhere[Q](buildAuthUserUserPermissionColumns(alias))
}

func buildAuthUserUserPermissionWhere[Q mysql.Filterable](cols authUserUserPermissionColumns) authUserUserPermissionWhere[Q] {
	return authUserUserPermissionWhere[Q]{
		ID:           mysql.Where[Q, int32](cols.ID),
		UserID:       mysql.Where[Q, int32](cols.UserID),
		PermissionID: mysql.Where[Q, int32](cols.PermissionID),
	}
}

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

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

		o.R.PermissionAuthPermission = rel

		if rel != nil {
			rel.R.PermissionAuthUserUserPermissions = AuthUserUserPermissionSlice{o}
		}
		return nil
	case "UserAuthUser":
		rel, ok := retrieved.(*AuthUser)
		if !ok {
			return fmt.Errorf("authUserUserPermission cannot load %T as %q", retrieved, name)
		}

		o.R.UserAuthUser = rel

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

type authUserUserPermissionPreloader struct {
	PermissionAuthPermission func(...mysql.PreloadOption) mysql.Preloader
	UserAuthUser             func(...mysql.PreloadOption) mysql.Preloader
}

func buildAuthUserUserPermissionPreloader() authUserUserPermissionPreloader {
	return authUserUserPermissionPreloader{
		PermissionAuthPermission: func(opts ...mysql.PreloadOption) mysql.Preloader {
			return mysql.Preload[*AuthPermission, AuthPermissionSlice](mysql.PreloadRel{
				Name: "PermissionAuthPermission",
				Sides: []mysql.PreloadSide{
					{
						From:        AuthUserUserPermissions,
						To:          AuthPermissions,
						FromColumns: []string{"permission_id"},
						ToColumns:   []string{"id"},
					},
				},
			}, AuthPermissions.Columns.Names(), opts...)
		},
		UserAuthUser: func(opts ...mysql.PreloadOption) mysql.Preloader {
			return mysql.Preload[*AuthUser, AuthUserSlice](mysql.PreloadRel{
				Name: "UserAuthUser",
				Sides: []mysql.PreloadSide{
					{
						From:        AuthUserUserPermissions,
						To:          AuthUsers,
						FromColumns: []string{"user_id"},
						ToColumns:   []string{"id"},
					},
				},
			}, AuthUsers.Columns.Names(), opts...)
		},
	}
}

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

func buildAuthUserUserPermissionThenLoader[Q orm.Loadable]() authUserUserPermissionThenLoader[Q] {
	type PermissionAuthPermissionLoadInterface interface {
		LoadPermissionAuthPermission(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error
	}
	type UserAuthUserLoadInterface interface {
		LoadUserAuthUser(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error
	}

	return authUserUserPermissionThenLoader[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...)
			},
		),
		UserAuthUser: thenLoadBuilder[Q](
			"UserAuthUser",
			func(ctx context.Context, exec bob.Executor, retrieved UserAuthUserLoadInterface, mods ...bob.Mod[*dialect.SelectQuery]) error {
				return retrieved.LoadUserAuthUser(ctx, exec, mods...)
			},
		),
	}
}

// LoadPermissionAuthPermission loads the authUserUserPermission's PermissionAuthPermission into the .R struct
func (o *AuthUserUserPermission) 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.PermissionAuthUserUserPermissions = AuthUserUserPermissionSlice{o}

	o.R.PermissionAuthPermission = related
	return nil
}

// LoadPermissionAuthPermission loads the authUserUserPermission's PermissionAuthPermission into the .R struct
func (os AuthUserUserPermissionSlice) 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.PermissionAuthUserUserPermissions = append(rel.R.PermissionAuthUserUserPermissions, o)

			o.R.PermissionAuthPermission = rel
			break
		}
	}

	return nil
}

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

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

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

	related.R.UserAuthUserUserPermissions = AuthUserUserPermissionSlice{o}

	o.R.UserAuthUser = related
	return nil
}

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

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

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

		for _, rel := range authUsers {

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

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

			o.R.UserAuthUser = rel
			break
		}
	}

	return nil
}

type authUserUserPermissionJoins[Q dialect.Joinable] struct {
	typ                      string
	PermissionAuthPermission modAs[Q, authPermissionColumns]
	UserAuthUser             modAs[Q, authUserColumns]
}

func (j authUserUserPermissionJoins[Q]) aliasedAs(alias string) authUserUserPermissionJoins[Q] {
	return buildAuthUserUserPermissionJoins[Q](buildAuthUserUserPermissionColumns(alias), j.typ)
}

func buildAuthUserUserPermissionJoins[Q dialect.Joinable](cols authUserUserPermissionColumns, typ string) authUserUserPermissionJoins[Q] {
	return authUserUserPermissionJoins[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
			},
		},
		UserAuthUser: modAs[Q, authUserColumns]{
			c: AuthUsers.Columns,
			f: func(to authUserColumns) bob.Mod[Q] {
				mods := make(mods.QueryMods[Q], 0, 1)

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

				return mods
			},
		},
	}
}
