// 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/mods"
	"github.com/Gleipnir-Technology/bob/orm"
	"github.com/Gleipnir-Technology/bob/types/pgtypes"
	enums "github.com/Gleipnir-Technology/nidus-sync/db/enums"
	"github.com/aarondl/opt/omit"
)

// Address is an object representing the database table.
type Address struct {
	Country    enums.Countrytype `db:"country" `
	Created    time.Time         `db:"created" `
	Geom       string            `db:"geom" `
	H3cell     string            `db:"h3cell" `
	ID         int32             `db:"id,pk" `
	Locality   string            `db:"locality" `
	Number     int32             `db:"number_" `
	PostalCode string            `db:"postal_code" `
	Street     string            `db:"street" `
	Unit       string            `db:"unit" `

	R addressR `db:"-" `

	C addressC `db:"-" `
}

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

// Addresses contains methods to work with the address table
var Addresses = psql.NewTablex[*Address, AddressSlice, *AddressSetter]("", "address", buildAddressColumns("address"))

// AddressesQuery is a query on the address table
type AddressesQuery = *psql.ViewQuery[*Address, AddressSlice]

// addressR is where relationships are stored.
type addressR struct {
	Residents ResidentSlice // resident.resident_address_id_fkey
	Site      *Site         // site.site_address_id_fkey
}

func buildAddressColumns(alias string) addressColumns {
	return addressColumns{
		ColumnsExpr: expr.NewColumnsExpr(
			"country", "created", "geom", "h3cell", "id", "locality", "number_", "postal_code", "street", "unit",
		).WithParent("address"),
		tableAlias: alias,
		Country:    psql.Quote(alias, "country"),
		Created:    psql.Quote(alias, "created"),
		Geom:       psql.Quote(alias, "geom"),
		H3cell:     psql.Quote(alias, "h3cell"),
		ID:         psql.Quote(alias, "id"),
		Locality:   psql.Quote(alias, "locality"),
		Number:     psql.Quote(alias, "number_"),
		PostalCode: psql.Quote(alias, "postal_code"),
		Street:     psql.Quote(alias, "street"),
		Unit:       psql.Quote(alias, "unit"),
	}
}

type addressColumns struct {
	expr.ColumnsExpr
	tableAlias string
	Country    psql.Expression
	Created    psql.Expression
	Geom       psql.Expression
	H3cell     psql.Expression
	ID         psql.Expression
	Locality   psql.Expression
	Number     psql.Expression
	PostalCode psql.Expression
	Street     psql.Expression
	Unit       psql.Expression
}

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

func (addressColumns) AliasedAs(alias string) addressColumns {
	return buildAddressColumns(alias)
}

// AddressSetter is used for insert/upsert/update operations
// All values are optional, and do not have to be set
// Generated columns are not included
type AddressSetter struct {
	Country    omit.Val[enums.Countrytype] `db:"country" `
	Created    omit.Val[time.Time]         `db:"created" `
	Geom       omit.Val[string]            `db:"geom" `
	H3cell     omit.Val[string]            `db:"h3cell" `
	ID         omit.Val[int32]             `db:"id,pk" `
	Locality   omit.Val[string]            `db:"locality" `
	Number     omit.Val[int32]             `db:"number_" `
	PostalCode omit.Val[string]            `db:"postal_code" `
	Street     omit.Val[string]            `db:"street" `
	Unit       omit.Val[string]            `db:"unit" `
}

func (s AddressSetter) SetColumns() []string {
	vals := make([]string, 0, 10)
	if s.Country.IsValue() {
		vals = append(vals, "country")
	}
	if s.Created.IsValue() {
		vals = append(vals, "created")
	}
	if s.Geom.IsValue() {
		vals = append(vals, "geom")
	}
	if s.H3cell.IsValue() {
		vals = append(vals, "h3cell")
	}
	if s.ID.IsValue() {
		vals = append(vals, "id")
	}
	if s.Locality.IsValue() {
		vals = append(vals, "locality")
	}
	if s.Number.IsValue() {
		vals = append(vals, "number_")
	}
	if s.PostalCode.IsValue() {
		vals = append(vals, "postal_code")
	}
	if s.Street.IsValue() {
		vals = append(vals, "street")
	}
	if s.Unit.IsValue() {
		vals = append(vals, "unit")
	}
	return vals
}

func (s AddressSetter) Overwrite(t *Address) {
	if s.Country.IsValue() {
		t.Country = s.Country.MustGet()
	}
	if s.Created.IsValue() {
		t.Created = s.Created.MustGet()
	}
	if s.Geom.IsValue() {
		t.Geom = s.Geom.MustGet()
	}
	if s.H3cell.IsValue() {
		t.H3cell = s.H3cell.MustGet()
	}
	if s.ID.IsValue() {
		t.ID = s.ID.MustGet()
	}
	if s.Locality.IsValue() {
		t.Locality = s.Locality.MustGet()
	}
	if s.Number.IsValue() {
		t.Number = s.Number.MustGet()
	}
	if s.PostalCode.IsValue() {
		t.PostalCode = s.PostalCode.MustGet()
	}
	if s.Street.IsValue() {
		t.Street = s.Street.MustGet()
	}
	if s.Unit.IsValue() {
		t.Unit = s.Unit.MustGet()
	}
}

func (s *AddressSetter) Apply(q *dialect.InsertQuery) {
	q.AppendHooks(func(ctx context.Context, exec bob.Executor) (context.Context, error) {
		return Addresses.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, 10)
		if s.Country.IsValue() {
			vals[0] = psql.Arg(s.Country.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.Geom.IsValue() {
			vals[2] = psql.Arg(s.Geom.MustGet())
		} else {
			vals[2] = psql.Raw("DEFAULT")
		}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

	return exprs
}

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

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

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

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

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

	return err
}

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

func (o *Address) pkEQ() dialect.Expression {
	return psql.Quote("address", "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 Address
func (o *Address) Update(ctx context.Context, exec bob.Executor, s *AddressSetter) error {
	v, err := Addresses.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 Address record with an executor
func (o *Address) Delete(ctx context.Context, exec bob.Executor) error {
	_, err := Addresses.Delete(dm.Where(o.pkEQ())).Exec(ctx, exec)
	return err
}

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

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

	return err
}

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

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

			return err
		}))

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

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

			return err
		}))

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

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

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

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

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

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

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

	o.copyMatchingRows(o2...)

	return nil
}

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

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

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

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

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

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

func insertAddressResidents0(ctx context.Context, exec bob.Executor, residents1 []*ResidentSetter, address0 *Address) (ResidentSlice, error) {
	for i := range residents1 {
		residents1[i].AddressID = omit.From(address0.ID)
	}

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

	return ret, nil
}

func attachAddressResidents0(ctx context.Context, exec bob.Executor, count int, residents1 ResidentSlice, address0 *Address) (ResidentSlice, error) {
	setter := &ResidentSetter{
		AddressID: omit.From(address0.ID),
	}

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

	return residents1, nil
}

func (address0 *Address) InsertResidents(ctx context.Context, exec bob.Executor, related ...*ResidentSetter) error {
	if len(related) == 0 {
		return nil
	}

	var err error

	residents1, err := insertAddressResidents0(ctx, exec, related, address0)
	if err != nil {
		return err
	}

	address0.R.Residents = append(address0.R.Residents, residents1...)

	for _, rel := range residents1 {
		rel.R.Address = address0
	}
	return nil
}

func (address0 *Address) AttachResidents(ctx context.Context, exec bob.Executor, related ...*Resident) error {
	if len(related) == 0 {
		return nil
	}

	var err error
	residents1 := ResidentSlice(related)

	_, err = attachAddressResidents0(ctx, exec, len(related), residents1, address0)
	if err != nil {
		return err
	}

	address0.R.Residents = append(address0.R.Residents, residents1...)

	for _, rel := range related {
		rel.R.Address = address0
	}

	return nil
}

func insertAddressSite0(ctx context.Context, exec bob.Executor, site1 *SiteSetter, address0 *Address) (*Site, error) {
	site1.AddressID = omit.From(address0.ID)

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

	return ret, nil
}

func attachAddressSite0(ctx context.Context, exec bob.Executor, count int, site1 *Site, address0 *Address) (*Site, error) {
	setter := &SiteSetter{
		AddressID: omit.From(address0.ID),
	}

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

	return site1, nil
}

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

	site1, err := insertAddressSite0(ctx, exec, related, address0)
	if err != nil {
		return err
	}

	address0.R.Site = site1

	site1.R.Address = address0

	return nil
}

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

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

	address0.R.Site = site1

	site1.R.Address = address0

	return nil
}

type addressWhere[Q psql.Filterable] struct {
	Country    psql.WhereMod[Q, enums.Countrytype]
	Created    psql.WhereMod[Q, time.Time]
	Geom       psql.WhereMod[Q, string]
	H3cell     psql.WhereMod[Q, string]
	ID         psql.WhereMod[Q, int32]
	Locality   psql.WhereMod[Q, string]
	Number     psql.WhereMod[Q, int32]
	PostalCode psql.WhereMod[Q, string]
	Street     psql.WhereMod[Q, string]
	Unit       psql.WhereMod[Q, string]
}

func (addressWhere[Q]) AliasedAs(alias string) addressWhere[Q] {
	return buildAddressWhere[Q](buildAddressColumns(alias))
}

func buildAddressWhere[Q psql.Filterable](cols addressColumns) addressWhere[Q] {
	return addressWhere[Q]{
		Country:    psql.Where[Q, enums.Countrytype](cols.Country),
		Created:    psql.Where[Q, time.Time](cols.Created),
		Geom:       psql.Where[Q, string](cols.Geom),
		H3cell:     psql.Where[Q, string](cols.H3cell),
		ID:         psql.Where[Q, int32](cols.ID),
		Locality:   psql.Where[Q, string](cols.Locality),
		Number:     psql.Where[Q, int32](cols.Number),
		PostalCode: psql.Where[Q, string](cols.PostalCode),
		Street:     psql.Where[Q, string](cols.Street),
		Unit:       psql.Where[Q, string](cols.Unit),
	}
}

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

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

		o.R.Residents = rels

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

		o.R.Site = rel

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

type addressPreloader struct {
	Site func(...psql.PreloadOption) psql.Preloader
}

func buildAddressPreloader() addressPreloader {
	return addressPreloader{
		Site: func(opts ...psql.PreloadOption) psql.Preloader {
			return psql.Preload[*Site, SiteSlice](psql.PreloadRel{
				Name: "Site",
				Sides: []psql.PreloadSide{
					{
						From:        Addresses,
						To:          Sites,
						FromColumns: []string{"id"},
						ToColumns:   []string{"address_id"},
					},
				},
			}, Sites.Columns.Names(), opts...)
		},
	}
}

type addressThenLoader[Q orm.Loadable] struct {
	Residents func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q]
	Site      func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q]
}

func buildAddressThenLoader[Q orm.Loadable]() addressThenLoader[Q] {
	type ResidentsLoadInterface interface {
		LoadResidents(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error
	}
	type SiteLoadInterface interface {
		LoadSite(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error
	}

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

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

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

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

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

	o.R.Residents = related
	return nil
}

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

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

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

		o.R.Residents = nil
	}

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

		for _, rel := range residents {

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

			rel.R.Address = o

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

	return nil
}

// LoadSite loads the address's Site into the .R struct
func (o *Address) 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.Address = o

	o.R.Site = related
	return nil
}

// LoadSite loads the address's Site into the .R struct
func (os AddressSlice) 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.ID == rel.AddressID) {
				continue
			}

			rel.R.Address = o

			o.R.Site = rel
			break
		}
	}

	return nil
}

// addressC is where relationship counts are stored.
type addressC struct {
	Residents *int64
}

// PreloadCount sets a count in the C struct by name
func (o *Address) PreloadCount(name string, count int64) error {
	if o == nil {
		return nil
	}

	switch name {
	case "Residents":
		o.C.Residents = &count
	}
	return nil
}

type addressCountPreloader struct {
	Residents func(...bob.Mod[*dialect.SelectQuery]) psql.Preloader
}

func buildAddressCountPreloader() addressCountPreloader {
	return addressCountPreloader{
		Residents: func(mods ...bob.Mod[*dialect.SelectQuery]) psql.Preloader {
			return countPreloader[*Address]("Residents", func(parent string) bob.Expression {
				// Build a correlated subquery: (SELECT COUNT(*) FROM related WHERE fk = parent.pk)
				if parent == "" {
					parent = Addresses.Alias()
				}

				subqueryMods := []bob.Mod[*dialect.SelectQuery]{
					sm.Columns(psql.Raw("count(*)")),

					sm.From(Residents.Name()),
					sm.Where(psql.Quote(Residents.Alias(), "address_id").EQ(psql.Quote(parent, "id"))),
				}
				subqueryMods = append(subqueryMods, mods...)
				return psql.Group(psql.Select(subqueryMods...).Expression)
			})
		},
	}
}

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

func buildAddressCountThenLoader[Q orm.Loadable]() addressCountThenLoader[Q] {
	type ResidentsCountInterface interface {
		LoadCountResidents(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error
	}

	return addressCountThenLoader[Q]{
		Residents: countThenLoadBuilder[Q](
			"Residents",
			func(ctx context.Context, exec bob.Executor, retrieved ResidentsCountInterface, mods ...bob.Mod[*dialect.SelectQuery]) error {
				return retrieved.LoadCountResidents(ctx, exec, mods...)
			},
		),
	}
}

// LoadCountResidents loads the count of Residents into the C struct
func (o *Address) LoadCountResidents(ctx context.Context, exec bob.Executor, mods ...bob.Mod[*dialect.SelectQuery]) error {
	if o == nil {
		return nil
	}

	count, err := o.Residents(mods...).Count(ctx, exec)
	if err != nil {
		return err
	}

	o.C.Residents = &count
	return nil
}

// LoadCountResidents loads the count of Residents for a slice
func (os AddressSlice) LoadCountResidents(ctx context.Context, exec bob.Executor, mods ...bob.Mod[*dialect.SelectQuery]) error {
	if len(os) == 0 {
		return nil
	}

	for _, o := range os {
		if err := o.LoadCountResidents(ctx, exec, mods...); err != nil {
			return err
		}
	}

	return nil
}

type addressJoins[Q dialect.Joinable] struct {
	typ       string
	Residents modAs[Q, residentColumns]
	Site      modAs[Q, siteColumns]
}

func (j addressJoins[Q]) aliasedAs(alias string) addressJoins[Q] {
	return buildAddressJoins[Q](buildAddressColumns(alias), j.typ)
}

func buildAddressJoins[Q dialect.Joinable](cols addressColumns, typ string) addressJoins[Q] {
	return addressJoins[Q]{
		typ: typ,
		Residents: modAs[Q, residentColumns]{
			c: Residents.Columns,
			f: func(to residentColumns) bob.Mod[Q] {
				mods := make(mods.QueryMods[Q], 0, 1)

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

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

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

				return mods
			},
		},
	}
}
