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

// PublicreportNotifyPhoneNuisanceOld is an object representing the database table.
type PublicreportNotifyPhoneNuisanceOld struct {
	Created    time.Time           `db:"created" `
	Deleted    null.Val[time.Time] `db:"deleted" `
	NuisanceID int32               `db:"nuisance_id,pk" `
	PhoneE164  string              `db:"phone_e164,pk" `

	R publicreportNotifyPhoneNuisanceOldR `db:"-" `
}

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

// PublicreportNotifyPhoneNuisanceOlds contains methods to work with the notify_phone_nuisance_old table
var PublicreportNotifyPhoneNuisanceOlds = psql.NewTablex[*PublicreportNotifyPhoneNuisanceOld, PublicreportNotifyPhoneNuisanceOldSlice, *PublicreportNotifyPhoneNuisanceOldSetter]("publicreport", "notify_phone_nuisance_old", buildPublicreportNotifyPhoneNuisanceOldColumns("publicreport.notify_phone_nuisance_old"))

// PublicreportNotifyPhoneNuisanceOldsQuery is a query on the notify_phone_nuisance_old table
type PublicreportNotifyPhoneNuisanceOldsQuery = *psql.ViewQuery[*PublicreportNotifyPhoneNuisanceOld, PublicreportNotifyPhoneNuisanceOldSlice]

// publicreportNotifyPhoneNuisanceOldR is where relationships are stored.
type publicreportNotifyPhoneNuisanceOldR struct {
	NuisanceNuisanceOld *PublicreportNuisanceOld // publicreport.notify_phone_nuisance_old.notify_phone_nuisance_nuisance_id_fkey
	PhoneE164Phone      *CommsPhone              // publicreport.notify_phone_nuisance_old.notify_phone_nuisance_phone_e164_fkey
}

func buildPublicreportNotifyPhoneNuisanceOldColumns(alias string) publicreportNotifyPhoneNuisanceOldColumns {
	return publicreportNotifyPhoneNuisanceOldColumns{
		ColumnsExpr: expr.NewColumnsExpr(
			"created", "deleted", "nuisance_id", "phone_e164",
		).WithParent("publicreport.notify_phone_nuisance_old"),
		tableAlias: alias,
		Created:    psql.Quote(alias, "created"),
		Deleted:    psql.Quote(alias, "deleted"),
		NuisanceID: psql.Quote(alias, "nuisance_id"),
		PhoneE164:  psql.Quote(alias, "phone_e164"),
	}
}

type publicreportNotifyPhoneNuisanceOldColumns struct {
	expr.ColumnsExpr
	tableAlias string
	Created    psql.Expression
	Deleted    psql.Expression
	NuisanceID psql.Expression
	PhoneE164  psql.Expression
}

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

func (publicreportNotifyPhoneNuisanceOldColumns) AliasedAs(alias string) publicreportNotifyPhoneNuisanceOldColumns {
	return buildPublicreportNotifyPhoneNuisanceOldColumns(alias)
}

// PublicreportNotifyPhoneNuisanceOldSetter is used for insert/upsert/update operations
// All values are optional, and do not have to be set
// Generated columns are not included
type PublicreportNotifyPhoneNuisanceOldSetter struct {
	Created    omit.Val[time.Time]     `db:"created" `
	Deleted    omitnull.Val[time.Time] `db:"deleted" `
	NuisanceID omit.Val[int32]         `db:"nuisance_id,pk" `
	PhoneE164  omit.Val[string]        `db:"phone_e164,pk" `
}

func (s PublicreportNotifyPhoneNuisanceOldSetter) SetColumns() []string {
	vals := make([]string, 0, 4)
	if s.Created.IsValue() {
		vals = append(vals, "created")
	}
	if !s.Deleted.IsUnset() {
		vals = append(vals, "deleted")
	}
	if s.NuisanceID.IsValue() {
		vals = append(vals, "nuisance_id")
	}
	if s.PhoneE164.IsValue() {
		vals = append(vals, "phone_e164")
	}
	return vals
}

func (s PublicreportNotifyPhoneNuisanceOldSetter) Overwrite(t *PublicreportNotifyPhoneNuisanceOld) {
	if s.Created.IsValue() {
		t.Created = s.Created.MustGet()
	}
	if !s.Deleted.IsUnset() {
		t.Deleted = s.Deleted.MustGetNull()
	}
	if s.NuisanceID.IsValue() {
		t.NuisanceID = s.NuisanceID.MustGet()
	}
	if s.PhoneE164.IsValue() {
		t.PhoneE164 = s.PhoneE164.MustGet()
	}
}

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

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

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

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

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

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

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

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

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

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

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

	return exprs
}

// FindPublicreportNotifyPhoneNuisanceOld retrieves a single record by primary key
// If cols is empty Find will return all columns.
func FindPublicreportNotifyPhoneNuisanceOld(ctx context.Context, exec bob.Executor, NuisanceIDPK int32, PhoneE164PK string, cols ...string) (*PublicreportNotifyPhoneNuisanceOld, error) {
	if len(cols) == 0 {
		return PublicreportNotifyPhoneNuisanceOlds.Query(
			sm.Where(PublicreportNotifyPhoneNuisanceOlds.Columns.NuisanceID.EQ(psql.Arg(NuisanceIDPK))),
			sm.Where(PublicreportNotifyPhoneNuisanceOlds.Columns.PhoneE164.EQ(psql.Arg(PhoneE164PK))),
		).One(ctx, exec)
	}

	return PublicreportNotifyPhoneNuisanceOlds.Query(
		sm.Where(PublicreportNotifyPhoneNuisanceOlds.Columns.NuisanceID.EQ(psql.Arg(NuisanceIDPK))),
		sm.Where(PublicreportNotifyPhoneNuisanceOlds.Columns.PhoneE164.EQ(psql.Arg(PhoneE164PK))),
		sm.Columns(PublicreportNotifyPhoneNuisanceOlds.Columns.Only(cols...)),
	).One(ctx, exec)
}

// PublicreportNotifyPhoneNuisanceOldExists checks the presence of a single record by primary key
func PublicreportNotifyPhoneNuisanceOldExists(ctx context.Context, exec bob.Executor, NuisanceIDPK int32, PhoneE164PK string) (bool, error) {
	return PublicreportNotifyPhoneNuisanceOlds.Query(
		sm.Where(PublicreportNotifyPhoneNuisanceOlds.Columns.NuisanceID.EQ(psql.Arg(NuisanceIDPK))),
		sm.Where(PublicreportNotifyPhoneNuisanceOlds.Columns.PhoneE164.EQ(psql.Arg(PhoneE164PK))),
	).Exists(ctx, exec)
}

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

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

	return err
}

// primaryKeyVals returns the primary key values of the PublicreportNotifyPhoneNuisanceOld
func (o *PublicreportNotifyPhoneNuisanceOld) primaryKeyVals() bob.Expression {
	return psql.ArgGroup(
		o.NuisanceID,
		o.PhoneE164,
	)
}

func (o *PublicreportNotifyPhoneNuisanceOld) pkEQ() dialect.Expression {
	return psql.Group(psql.Quote("publicreport.notify_phone_nuisance_old", "nuisance_id"), psql.Quote("publicreport.notify_phone_nuisance_old", "phone_e164")).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 PublicreportNotifyPhoneNuisanceOld
func (o *PublicreportNotifyPhoneNuisanceOld) Update(ctx context.Context, exec bob.Executor, s *PublicreportNotifyPhoneNuisanceOldSetter) error {
	v, err := PublicreportNotifyPhoneNuisanceOlds.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 PublicreportNotifyPhoneNuisanceOld record with an executor
func (o *PublicreportNotifyPhoneNuisanceOld) Delete(ctx context.Context, exec bob.Executor) error {
	_, err := PublicreportNotifyPhoneNuisanceOlds.Delete(dm.Where(o.pkEQ())).Exec(ctx, exec)
	return err
}

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

	return nil
}

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

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

	return err
}

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

	return psql.Group(psql.Quote("publicreport.notify_phone_nuisance_old", "nuisance_id"), psql.Quote("publicreport.notify_phone_nuisance_old", "phone_e164")).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 PublicreportNotifyPhoneNuisanceOldSlice) copyMatchingRows(from ...*PublicreportNotifyPhoneNuisanceOld) {
	for i, old := range o {
		for _, new := range from {
			if new.NuisanceID != old.NuisanceID {
				continue
			}
			if new.PhoneE164 != old.PhoneE164 {
				continue
			}
			new.R = old.R
			o[i] = new
			break
		}
	}
}

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

			return err
		}))

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

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

			return err
		}))

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

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

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

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

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

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

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

	o.copyMatchingRows(o2...)

	return nil
}

// NuisanceNuisanceOld starts a query for related objects on publicreport.nuisance_old
func (o *PublicreportNotifyPhoneNuisanceOld) NuisanceNuisanceOld(mods ...bob.Mod[*dialect.SelectQuery]) PublicreportNuisanceOldsQuery {
	return PublicreportNuisanceOlds.Query(append(mods,
		sm.Where(PublicreportNuisanceOlds.Columns.ID.EQ(psql.Arg(o.NuisanceID))),
	)...)
}

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

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

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

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

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

func attachPublicreportNotifyPhoneNuisanceOldNuisanceNuisanceOld0(ctx context.Context, exec bob.Executor, count int, publicreportNotifyPhoneNuisanceOld0 *PublicreportNotifyPhoneNuisanceOld, publicreportNuisanceOld1 *PublicreportNuisanceOld) (*PublicreportNotifyPhoneNuisanceOld, error) {
	setter := &PublicreportNotifyPhoneNuisanceOldSetter{
		NuisanceID: omit.From(publicreportNuisanceOld1.ID),
	}

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

	return publicreportNotifyPhoneNuisanceOld0, nil
}

func (publicreportNotifyPhoneNuisanceOld0 *PublicreportNotifyPhoneNuisanceOld) InsertNuisanceNuisanceOld(ctx context.Context, exec bob.Executor, related *PublicreportNuisanceOldSetter) error {
	var err error

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

	_, err = attachPublicreportNotifyPhoneNuisanceOldNuisanceNuisanceOld0(ctx, exec, 1, publicreportNotifyPhoneNuisanceOld0, publicreportNuisanceOld1)
	if err != nil {
		return err
	}

	publicreportNotifyPhoneNuisanceOld0.R.NuisanceNuisanceOld = publicreportNuisanceOld1

	publicreportNuisanceOld1.R.NuisanceNotifyPhoneNuisanceOlds = append(publicreportNuisanceOld1.R.NuisanceNotifyPhoneNuisanceOlds, publicreportNotifyPhoneNuisanceOld0)

	return nil
}

func (publicreportNotifyPhoneNuisanceOld0 *PublicreportNotifyPhoneNuisanceOld) AttachNuisanceNuisanceOld(ctx context.Context, exec bob.Executor, publicreportNuisanceOld1 *PublicreportNuisanceOld) error {
	var err error

	_, err = attachPublicreportNotifyPhoneNuisanceOldNuisanceNuisanceOld0(ctx, exec, 1, publicreportNotifyPhoneNuisanceOld0, publicreportNuisanceOld1)
	if err != nil {
		return err
	}

	publicreportNotifyPhoneNuisanceOld0.R.NuisanceNuisanceOld = publicreportNuisanceOld1

	publicreportNuisanceOld1.R.NuisanceNotifyPhoneNuisanceOlds = append(publicreportNuisanceOld1.R.NuisanceNotifyPhoneNuisanceOlds, publicreportNotifyPhoneNuisanceOld0)

	return nil
}

func attachPublicreportNotifyPhoneNuisanceOldPhoneE164Phone0(ctx context.Context, exec bob.Executor, count int, publicreportNotifyPhoneNuisanceOld0 *PublicreportNotifyPhoneNuisanceOld, commsPhone1 *CommsPhone) (*PublicreportNotifyPhoneNuisanceOld, error) {
	setter := &PublicreportNotifyPhoneNuisanceOldSetter{
		PhoneE164: omit.From(commsPhone1.E164),
	}

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

	return publicreportNotifyPhoneNuisanceOld0, nil
}

func (publicreportNotifyPhoneNuisanceOld0 *PublicreportNotifyPhoneNuisanceOld) InsertPhoneE164Phone(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 = attachPublicreportNotifyPhoneNuisanceOldPhoneE164Phone0(ctx, exec, 1, publicreportNotifyPhoneNuisanceOld0, commsPhone1)
	if err != nil {
		return err
	}

	publicreportNotifyPhoneNuisanceOld0.R.PhoneE164Phone = commsPhone1

	commsPhone1.R.PhoneE164NotifyPhoneNuisanceOlds = append(commsPhone1.R.PhoneE164NotifyPhoneNuisanceOlds, publicreportNotifyPhoneNuisanceOld0)

	return nil
}

func (publicreportNotifyPhoneNuisanceOld0 *PublicreportNotifyPhoneNuisanceOld) AttachPhoneE164Phone(ctx context.Context, exec bob.Executor, commsPhone1 *CommsPhone) error {
	var err error

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

	publicreportNotifyPhoneNuisanceOld0.R.PhoneE164Phone = commsPhone1

	commsPhone1.R.PhoneE164NotifyPhoneNuisanceOlds = append(commsPhone1.R.PhoneE164NotifyPhoneNuisanceOlds, publicreportNotifyPhoneNuisanceOld0)

	return nil
}

type publicreportNotifyPhoneNuisanceOldWhere[Q psql.Filterable] struct {
	Created    psql.WhereMod[Q, time.Time]
	Deleted    psql.WhereNullMod[Q, time.Time]
	NuisanceID psql.WhereMod[Q, int32]
	PhoneE164  psql.WhereMod[Q, string]
}

func (publicreportNotifyPhoneNuisanceOldWhere[Q]) AliasedAs(alias string) publicreportNotifyPhoneNuisanceOldWhere[Q] {
	return buildPublicreportNotifyPhoneNuisanceOldWhere[Q](buildPublicreportNotifyPhoneNuisanceOldColumns(alias))
}

func buildPublicreportNotifyPhoneNuisanceOldWhere[Q psql.Filterable](cols publicreportNotifyPhoneNuisanceOldColumns) publicreportNotifyPhoneNuisanceOldWhere[Q] {
	return publicreportNotifyPhoneNuisanceOldWhere[Q]{
		Created:    psql.Where[Q, time.Time](cols.Created),
		Deleted:    psql.WhereNull[Q, time.Time](cols.Deleted),
		NuisanceID: psql.Where[Q, int32](cols.NuisanceID),
		PhoneE164:  psql.Where[Q, string](cols.PhoneE164),
	}
}

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

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

		o.R.NuisanceNuisanceOld = rel

		if rel != nil {
			rel.R.NuisanceNotifyPhoneNuisanceOlds = PublicreportNotifyPhoneNuisanceOldSlice{o}
		}
		return nil
	case "PhoneE164Phone":
		rel, ok := retrieved.(*CommsPhone)
		if !ok {
			return fmt.Errorf("publicreportNotifyPhoneNuisanceOld cannot load %T as %q", retrieved, name)
		}

		o.R.PhoneE164Phone = rel

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

type publicreportNotifyPhoneNuisanceOldPreloader struct {
	NuisanceNuisanceOld func(...psql.PreloadOption) psql.Preloader
	PhoneE164Phone      func(...psql.PreloadOption) psql.Preloader
}

func buildPublicreportNotifyPhoneNuisanceOldPreloader() publicreportNotifyPhoneNuisanceOldPreloader {
	return publicreportNotifyPhoneNuisanceOldPreloader{
		NuisanceNuisanceOld: func(opts ...psql.PreloadOption) psql.Preloader {
			return psql.Preload[*PublicreportNuisanceOld, PublicreportNuisanceOldSlice](psql.PreloadRel{
				Name: "NuisanceNuisanceOld",
				Sides: []psql.PreloadSide{
					{
						From:        PublicreportNotifyPhoneNuisanceOlds,
						To:          PublicreportNuisanceOlds,
						FromColumns: []string{"nuisance_id"},
						ToColumns:   []string{"id"},
					},
				},
			}, PublicreportNuisanceOlds.Columns.Names(), opts...)
		},
		PhoneE164Phone: func(opts ...psql.PreloadOption) psql.Preloader {
			return psql.Preload[*CommsPhone, CommsPhoneSlice](psql.PreloadRel{
				Name: "PhoneE164Phone",
				Sides: []psql.PreloadSide{
					{
						From:        PublicreportNotifyPhoneNuisanceOlds,
						To:          CommsPhones,
						FromColumns: []string{"phone_e164"},
						ToColumns:   []string{"e164"},
					},
				},
			}, CommsPhones.Columns.Names(), opts...)
		},
	}
}

type publicreportNotifyPhoneNuisanceOldThenLoader[Q orm.Loadable] struct {
	NuisanceNuisanceOld func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q]
	PhoneE164Phone      func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q]
}

func buildPublicreportNotifyPhoneNuisanceOldThenLoader[Q orm.Loadable]() publicreportNotifyPhoneNuisanceOldThenLoader[Q] {
	type NuisanceNuisanceOldLoadInterface interface {
		LoadNuisanceNuisanceOld(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error
	}
	type PhoneE164PhoneLoadInterface interface {
		LoadPhoneE164Phone(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error
	}

	return publicreportNotifyPhoneNuisanceOldThenLoader[Q]{
		NuisanceNuisanceOld: thenLoadBuilder[Q](
			"NuisanceNuisanceOld",
			func(ctx context.Context, exec bob.Executor, retrieved NuisanceNuisanceOldLoadInterface, mods ...bob.Mod[*dialect.SelectQuery]) error {
				return retrieved.LoadNuisanceNuisanceOld(ctx, exec, mods...)
			},
		),
		PhoneE164Phone: thenLoadBuilder[Q](
			"PhoneE164Phone",
			func(ctx context.Context, exec bob.Executor, retrieved PhoneE164PhoneLoadInterface, mods ...bob.Mod[*dialect.SelectQuery]) error {
				return retrieved.LoadPhoneE164Phone(ctx, exec, mods...)
			},
		),
	}
}

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

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

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

	related.R.NuisanceNotifyPhoneNuisanceOlds = PublicreportNotifyPhoneNuisanceOldSlice{o}

	o.R.NuisanceNuisanceOld = related
	return nil
}

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

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

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

		for _, rel := range publicreportNuisanceOlds {

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

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

			o.R.NuisanceNuisanceOld = rel
			break
		}
	}

	return nil
}

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

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

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

	related.R.PhoneE164NotifyPhoneNuisanceOlds = PublicreportNotifyPhoneNuisanceOldSlice{o}

	o.R.PhoneE164Phone = related
	return nil
}

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

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

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

		for _, rel := range commsPhones {

			if !(o.PhoneE164 == rel.E164) {
				continue
			}

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

			o.R.PhoneE164Phone = rel
			break
		}
	}

	return nil
}
