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

package models

import (
	"context"
	"fmt"
	"io"
	"time"

	"github.com/Gleipnir-Technology/bob"
	"github.com/Gleipnir-Technology/bob/dialect/psql"
	"github.com/Gleipnir-Technology/bob/dialect/psql/dialect"
	"github.com/Gleipnir-Technology/bob/dialect/psql/dm"
	"github.com/Gleipnir-Technology/bob/dialect/psql/sm"
	"github.com/Gleipnir-Technology/bob/dialect/psql/um"
	"github.com/Gleipnir-Technology/bob/expr"
	"github.com/Gleipnir-Technology/bob/orm"
	"github.com/Gleipnir-Technology/bob/types/pgtypes"
	"github.com/aarondl/opt/null"
	"github.com/aarondl/opt/omit"
	"github.com/aarondl/opt/omitnull"
)

// Resident is an object representing the database table.
type Resident struct {
	AddressID   int32            `db:"address_id" `
	Created     time.Time        `db:"created" `
	Creator     int32            `db:"creator" `
	ID          int32            `db:"id,pk" `
	Name        string           `db:"name" `
	PhoneMobile null.Val[string] `db:"phone_mobile" `
	SiteID      int32            `db:"site_id" `

	R residentR `db:"-" `
}

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

// Residents contains methods to work with the resident table
var Residents = psql.NewTablex[*Resident, ResidentSlice, *ResidentSetter]("", "resident", buildResidentColumns("resident"))

// ResidentsQuery is a query on the resident table
type ResidentsQuery = *psql.ViewQuery[*Resident, ResidentSlice]

// residentR is where relationships are stored.
type residentR struct {
	Address          *Address    // resident.resident_address_id_fkey
	CreatorUser      *User       // resident.resident_creator_fkey
	PhoneMobilePhone *CommsPhone // resident.resident_phone_mobile_fkey
	Site             *Site       // resident.resident_site_id_fkey
}

func buildResidentColumns(alias string) residentColumns {
	return residentColumns{
		ColumnsExpr: expr.NewColumnsExpr(
			"address_id", "created", "creator", "id", "name", "phone_mobile", "site_id",
		).WithParent("resident"),
		tableAlias:  alias,
		AddressID:   psql.Quote(alias, "address_id"),
		Created:     psql.Quote(alias, "created"),
		Creator:     psql.Quote(alias, "creator"),
		ID:          psql.Quote(alias, "id"),
		Name:        psql.Quote(alias, "name"),
		PhoneMobile: psql.Quote(alias, "phone_mobile"),
		SiteID:      psql.Quote(alias, "site_id"),
	}
}

type residentColumns struct {
	expr.ColumnsExpr
	tableAlias  string
	AddressID   psql.Expression
	Created     psql.Expression
	Creator     psql.Expression
	ID          psql.Expression
	Name        psql.Expression
	PhoneMobile psql.Expression
	SiteID      psql.Expression
}

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

func (residentColumns) AliasedAs(alias string) residentColumns {
	return buildResidentColumns(alias)
}

// ResidentSetter is used for insert/upsert/update operations
// All values are optional, and do not have to be set
// Generated columns are not included
type ResidentSetter struct {
	AddressID   omit.Val[int32]      `db:"address_id" `
	Created     omit.Val[time.Time]  `db:"created" `
	Creator     omit.Val[int32]      `db:"creator" `
	ID          omit.Val[int32]      `db:"id,pk" `
	Name        omit.Val[string]     `db:"name" `
	PhoneMobile omitnull.Val[string] `db:"phone_mobile" `
	SiteID      omit.Val[int32]      `db:"site_id" `
}

func (s ResidentSetter) SetColumns() []string {
	vals := make([]string, 0, 7)
	if s.AddressID.IsValue() {
		vals = append(vals, "address_id")
	}
	if s.Created.IsValue() {
		vals = append(vals, "created")
	}
	if s.Creator.IsValue() {
		vals = append(vals, "creator")
	}
	if s.ID.IsValue() {
		vals = append(vals, "id")
	}
	if s.Name.IsValue() {
		vals = append(vals, "name")
	}
	if !s.PhoneMobile.IsUnset() {
		vals = append(vals, "phone_mobile")
	}
	if s.SiteID.IsValue() {
		vals = append(vals, "site_id")
	}
	return vals
}

func (s ResidentSetter) Overwrite(t *Resident) {
	if s.AddressID.IsValue() {
		t.AddressID = s.AddressID.MustGet()
	}
	if s.Created.IsValue() {
		t.Created = s.Created.MustGet()
	}
	if s.Creator.IsValue() {
		t.Creator = s.Creator.MustGet()
	}
	if s.ID.IsValue() {
		t.ID = s.ID.MustGet()
	}
	if s.Name.IsValue() {
		t.Name = s.Name.MustGet()
	}
	if !s.PhoneMobile.IsUnset() {
		t.PhoneMobile = s.PhoneMobile.MustGetNull()
	}
	if s.SiteID.IsValue() {
		t.SiteID = s.SiteID.MustGet()
	}
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

	return exprs
}

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

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

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

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

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

	return err
}

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

func (o *Resident) pkEQ() dialect.Expression {
	return psql.Quote("resident", "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 Resident
func (o *Resident) Update(ctx context.Context, exec bob.Executor, s *ResidentSetter) error {
	v, err := Residents.Update(s.UpdateMod(), um.Where(o.pkEQ())).One(ctx, exec)
	if err != nil {
		return err
	}

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

	return nil
}

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

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

	return nil
}

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

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

	return err
}

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

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

			return err
		}))

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

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

			return err
		}))

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

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

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

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

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

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

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

	o.copyMatchingRows(o2...)

	return nil
}

// Address starts a query for related objects on address
func (o *Resident) Address(mods ...bob.Mod[*dialect.SelectQuery]) AddressesQuery {
	return Addresses.Query(append(mods,
		sm.Where(Addresses.Columns.ID.EQ(psql.Arg(o.AddressID))),
	)...)
}

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

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

// CreatorUser starts a query for related objects on user_
func (o *Resident) CreatorUser(mods ...bob.Mod[*dialect.SelectQuery]) UsersQuery {
	return Users.Query(append(mods,
		sm.Where(Users.Columns.ID.EQ(psql.Arg(o.Creator))),
	)...)
}

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

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

// PhoneMobilePhone starts a query for related objects on comms.phone
func (o *Resident) PhoneMobilePhone(mods ...bob.Mod[*dialect.SelectQuery]) CommsPhonesQuery {
	return CommsPhones.Query(append(mods,
		sm.Where(CommsPhones.Columns.E164.EQ(psql.Arg(o.PhoneMobile))),
	)...)
}

func (os ResidentSlice) PhoneMobilePhone(mods ...bob.Mod[*dialect.SelectQuery]) CommsPhonesQuery {
	pkPhoneMobile := make(pgtypes.Array[null.Val[string]], 0, len(os))
	for _, o := range os {
		if o == nil {
			continue
		}
		pkPhoneMobile = append(pkPhoneMobile, o.PhoneMobile)
	}
	PKArgExpr := psql.Select(sm.Columns(
		psql.F("unnest", psql.Cast(psql.Arg(pkPhoneMobile), "text[]")),
	))

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

// Site starts a query for related objects on site
func (o *Resident) Site(mods ...bob.Mod[*dialect.SelectQuery]) SitesQuery {
	return Sites.Query(append(mods,
		sm.Where(Sites.Columns.ID.EQ(psql.Arg(o.SiteID))),
	)...)
}

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

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

func attachResidentAddress0(ctx context.Context, exec bob.Executor, count int, resident0 *Resident, address1 *Address) (*Resident, error) {
	setter := &ResidentSetter{
		AddressID: omit.From(address1.ID),
	}

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

	return resident0, nil
}

func (resident0 *Resident) InsertAddress(ctx context.Context, exec bob.Executor, related *AddressSetter) error {
	var err error

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

	_, err = attachResidentAddress0(ctx, exec, 1, resident0, address1)
	if err != nil {
		return err
	}

	resident0.R.Address = address1

	address1.R.Residents = append(address1.R.Residents, resident0)

	return nil
}

func (resident0 *Resident) AttachAddress(ctx context.Context, exec bob.Executor, address1 *Address) error {
	var err error

	_, err = attachResidentAddress0(ctx, exec, 1, resident0, address1)
	if err != nil {
		return err
	}

	resident0.R.Address = address1

	address1.R.Residents = append(address1.R.Residents, resident0)

	return nil
}

func attachResidentCreatorUser0(ctx context.Context, exec bob.Executor, count int, resident0 *Resident, user1 *User) (*Resident, error) {
	setter := &ResidentSetter{
		Creator: omit.From(user1.ID),
	}

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

	return resident0, nil
}

func (resident0 *Resident) InsertCreatorUser(ctx context.Context, exec bob.Executor, related *UserSetter) error {
	var err error

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

	_, err = attachResidentCreatorUser0(ctx, exec, 1, resident0, user1)
	if err != nil {
		return err
	}

	resident0.R.CreatorUser = user1

	user1.R.CreatorResidents = append(user1.R.CreatorResidents, resident0)

	return nil
}

func (resident0 *Resident) AttachCreatorUser(ctx context.Context, exec bob.Executor, user1 *User) error {
	var err error

	_, err = attachResidentCreatorUser0(ctx, exec, 1, resident0, user1)
	if err != nil {
		return err
	}

	resident0.R.CreatorUser = user1

	user1.R.CreatorResidents = append(user1.R.CreatorResidents, resident0)

	return nil
}

func attachResidentPhoneMobilePhone0(ctx context.Context, exec bob.Executor, count int, resident0 *Resident, commsPhone1 *CommsPhone) (*Resident, error) {
	setter := &ResidentSetter{
		PhoneMobile: omitnull.From(commsPhone1.E164),
	}

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

	return resident0, nil
}

func (resident0 *Resident) InsertPhoneMobilePhone(ctx context.Context, exec bob.Executor, related *CommsPhoneSetter) error {
	var err error

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

	_, err = attachResidentPhoneMobilePhone0(ctx, exec, 1, resident0, commsPhone1)
	if err != nil {
		return err
	}

	resident0.R.PhoneMobilePhone = commsPhone1

	commsPhone1.R.PhoneMobileResidents = append(commsPhone1.R.PhoneMobileResidents, resident0)

	return nil
}

func (resident0 *Resident) AttachPhoneMobilePhone(ctx context.Context, exec bob.Executor, commsPhone1 *CommsPhone) error {
	var err error

	_, err = attachResidentPhoneMobilePhone0(ctx, exec, 1, resident0, commsPhone1)
	if err != nil {
		return err
	}

	resident0.R.PhoneMobilePhone = commsPhone1

	commsPhone1.R.PhoneMobileResidents = append(commsPhone1.R.PhoneMobileResidents, resident0)

	return nil
}

func attachResidentSite0(ctx context.Context, exec bob.Executor, count int, resident0 *Resident, site1 *Site) (*Resident, error) {
	setter := &ResidentSetter{
		SiteID: omit.From(site1.ID),
	}

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

	return resident0, nil
}

func (resident0 *Resident) InsertSite(ctx context.Context, exec bob.Executor, related *SiteSetter) error {
	var err error

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

	_, err = attachResidentSite0(ctx, exec, 1, resident0, site1)
	if err != nil {
		return err
	}

	resident0.R.Site = site1

	site1.R.Residents = append(site1.R.Residents, resident0)

	return nil
}

func (resident0 *Resident) AttachSite(ctx context.Context, exec bob.Executor, site1 *Site) error {
	var err error

	_, err = attachResidentSite0(ctx, exec, 1, resident0, site1)
	if err != nil {
		return err
	}

	resident0.R.Site = site1

	site1.R.Residents = append(site1.R.Residents, resident0)

	return nil
}

type residentWhere[Q psql.Filterable] struct {
	AddressID   psql.WhereMod[Q, int32]
	Created     psql.WhereMod[Q, time.Time]
	Creator     psql.WhereMod[Q, int32]
	ID          psql.WhereMod[Q, int32]
	Name        psql.WhereMod[Q, string]
	PhoneMobile psql.WhereNullMod[Q, string]
	SiteID      psql.WhereMod[Q, int32]
}

func (residentWhere[Q]) AliasedAs(alias string) residentWhere[Q] {
	return buildResidentWhere[Q](buildResidentColumns(alias))
}

func buildResidentWhere[Q psql.Filterable](cols residentColumns) residentWhere[Q] {
	return residentWhere[Q]{
		AddressID:   psql.Where[Q, int32](cols.AddressID),
		Created:     psql.Where[Q, time.Time](cols.Created),
		Creator:     psql.Where[Q, int32](cols.Creator),
		ID:          psql.Where[Q, int32](cols.ID),
		Name:        psql.Where[Q, string](cols.Name),
		PhoneMobile: psql.WhereNull[Q, string](cols.PhoneMobile),
		SiteID:      psql.Where[Q, int32](cols.SiteID),
	}
}

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

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

		o.R.Address = rel

		if rel != nil {
			rel.R.Residents = ResidentSlice{o}
		}
		return nil
	case "CreatorUser":
		rel, ok := retrieved.(*User)
		if !ok {
			return fmt.Errorf("resident cannot load %T as %q", retrieved, name)
		}

		o.R.CreatorUser = rel

		if rel != nil {
			rel.R.CreatorResidents = ResidentSlice{o}
		}
		return nil
	case "PhoneMobilePhone":
		rel, ok := retrieved.(*CommsPhone)
		if !ok {
			return fmt.Errorf("resident cannot load %T as %q", retrieved, name)
		}

		o.R.PhoneMobilePhone = rel

		if rel != nil {
			rel.R.PhoneMobileResidents = ResidentSlice{o}
		}
		return nil
	case "Site":
		rel, ok := retrieved.(*Site)
		if !ok {
			return fmt.Errorf("resident cannot load %T as %q", retrieved, name)
		}

		o.R.Site = rel

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

type residentPreloader struct {
	Address          func(...psql.PreloadOption) psql.Preloader
	CreatorUser      func(...psql.PreloadOption) psql.Preloader
	PhoneMobilePhone func(...psql.PreloadOption) psql.Preloader
	Site             func(...psql.PreloadOption) psql.Preloader
}

func buildResidentPreloader() residentPreloader {
	return residentPreloader{
		Address: func(opts ...psql.PreloadOption) psql.Preloader {
			return psql.Preload[*Address, AddressSlice](psql.PreloadRel{
				Name: "Address",
				Sides: []psql.PreloadSide{
					{
						From:        Residents,
						To:          Addresses,
						FromColumns: []string{"address_id"},
						ToColumns:   []string{"id"},
					},
				},
			}, Addresses.Columns.Names(), opts...)
		},
		CreatorUser: func(opts ...psql.PreloadOption) psql.Preloader {
			return psql.Preload[*User, UserSlice](psql.PreloadRel{
				Name: "CreatorUser",
				Sides: []psql.PreloadSide{
					{
						From:        Residents,
						To:          Users,
						FromColumns: []string{"creator"},
						ToColumns:   []string{"id"},
					},
				},
			}, Users.Columns.Names(), opts...)
		},
		PhoneMobilePhone: func(opts ...psql.PreloadOption) psql.Preloader {
			return psql.Preload[*CommsPhone, CommsPhoneSlice](psql.PreloadRel{
				Name: "PhoneMobilePhone",
				Sides: []psql.PreloadSide{
					{
						From:        Residents,
						To:          CommsPhones,
						FromColumns: []string{"phone_mobile"},
						ToColumns:   []string{"e164"},
					},
				},
			}, CommsPhones.Columns.Names(), opts...)
		},
		Site: func(opts ...psql.PreloadOption) psql.Preloader {
			return psql.Preload[*Site, SiteSlice](psql.PreloadRel{
				Name: "Site",
				Sides: []psql.PreloadSide{
					{
						From:        Residents,
						To:          Sites,
						FromColumns: []string{"site_id"},
						ToColumns:   []string{"id"},
					},
				},
			}, Sites.Columns.Names(), opts...)
		},
	}
}

type residentThenLoader[Q orm.Loadable] struct {
	Address          func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q]
	CreatorUser      func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q]
	PhoneMobilePhone func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q]
	Site             func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q]
}

func buildResidentThenLoader[Q orm.Loadable]() residentThenLoader[Q] {
	type AddressLoadInterface interface {
		LoadAddress(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error
	}
	type CreatorUserLoadInterface interface {
		LoadCreatorUser(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error
	}
	type PhoneMobilePhoneLoadInterface interface {
		LoadPhoneMobilePhone(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error
	}
	type SiteLoadInterface interface {
		LoadSite(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error
	}

	return residentThenLoader[Q]{
		Address: thenLoadBuilder[Q](
			"Address",
			func(ctx context.Context, exec bob.Executor, retrieved AddressLoadInterface, mods ...bob.Mod[*dialect.SelectQuery]) error {
				return retrieved.LoadAddress(ctx, exec, mods...)
			},
		),
		CreatorUser: thenLoadBuilder[Q](
			"CreatorUser",
			func(ctx context.Context, exec bob.Executor, retrieved CreatorUserLoadInterface, mods ...bob.Mod[*dialect.SelectQuery]) error {
				return retrieved.LoadCreatorUser(ctx, exec, mods...)
			},
		),
		PhoneMobilePhone: thenLoadBuilder[Q](
			"PhoneMobilePhone",
			func(ctx context.Context, exec bob.Executor, retrieved PhoneMobilePhoneLoadInterface, mods ...bob.Mod[*dialect.SelectQuery]) error {
				return retrieved.LoadPhoneMobilePhone(ctx, exec, mods...)
			},
		),
		Site: thenLoadBuilder[Q](
			"Site",
			func(ctx context.Context, exec bob.Executor, retrieved SiteLoadInterface, mods ...bob.Mod[*dialect.SelectQuery]) error {
				return retrieved.LoadSite(ctx, exec, mods...)
			},
		),
	}
}

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

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

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

	related.R.Residents = ResidentSlice{o}

	o.R.Address = related
	return nil
}

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

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

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

		for _, rel := range addresses {

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

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

			o.R.Address = rel
			break
		}
	}

	return nil
}

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

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

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

	related.R.CreatorResidents = ResidentSlice{o}

	o.R.CreatorUser = related
	return nil
}

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

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

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

		for _, rel := range users {

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

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

			o.R.CreatorUser = rel
			break
		}
	}

	return nil
}

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

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

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

	related.R.PhoneMobileResidents = ResidentSlice{o}

	o.R.PhoneMobilePhone = related
	return nil
}

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

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

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

		for _, rel := range commsPhones {
			if !o.PhoneMobile.IsValue() {
				continue
			}

			if !(o.PhoneMobile.IsValue() && o.PhoneMobile.MustGet() == rel.E164) {
				continue
			}

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

			o.R.PhoneMobilePhone = rel
			break
		}
	}

	return nil
}

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

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

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

	related.R.Residents = ResidentSlice{o}

	o.R.Site = related
	return nil
}

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

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

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

		for _, rel := range sites {

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

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

			o.R.Site = rel
			break
		}
	}

	return nil
}
