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

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

	R publicreportNotifyEmailNuisanceOldR `db:"-" `
}

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

// PublicreportNotifyEmailNuisanceOlds contains methods to work with the notify_email_nuisance_old table
var PublicreportNotifyEmailNuisanceOlds = psql.NewTablex[*PublicreportNotifyEmailNuisanceOld, PublicreportNotifyEmailNuisanceOldSlice, *PublicreportNotifyEmailNuisanceOldSetter]("publicreport", "notify_email_nuisance_old", buildPublicreportNotifyEmailNuisanceOldColumns("publicreport.notify_email_nuisance_old"))

// PublicreportNotifyEmailNuisanceOldsQuery is a query on the notify_email_nuisance_old table
type PublicreportNotifyEmailNuisanceOldsQuery = *psql.ViewQuery[*PublicreportNotifyEmailNuisanceOld, PublicreportNotifyEmailNuisanceOldSlice]

// publicreportNotifyEmailNuisanceOldR is where relationships are stored.
type publicreportNotifyEmailNuisanceOldR struct {
	EmailAddressEmailContact *CommsEmailContact       // publicreport.notify_email_nuisance_old.notify_email_nuisance_email_address_fkey
	NuisanceNuisanceOld      *PublicreportNuisanceOld // publicreport.notify_email_nuisance_old.notify_email_nuisance_nuisance_id_fkey
}

func buildPublicreportNotifyEmailNuisanceOldColumns(alias string) publicreportNotifyEmailNuisanceOldColumns {
	return publicreportNotifyEmailNuisanceOldColumns{
		ColumnsExpr: expr.NewColumnsExpr(
			"created", "deleted", "nuisance_id", "email_address",
		).WithParent("publicreport.notify_email_nuisance_old"),
		tableAlias:   alias,
		Created:      psql.Quote(alias, "created"),
		Deleted:      psql.Quote(alias, "deleted"),
		NuisanceID:   psql.Quote(alias, "nuisance_id"),
		EmailAddress: psql.Quote(alias, "email_address"),
	}
}

type publicreportNotifyEmailNuisanceOldColumns struct {
	expr.ColumnsExpr
	tableAlias   string
	Created      psql.Expression
	Deleted      psql.Expression
	NuisanceID   psql.Expression
	EmailAddress psql.Expression
}

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

func (publicreportNotifyEmailNuisanceOldColumns) AliasedAs(alias string) publicreportNotifyEmailNuisanceOldColumns {
	return buildPublicreportNotifyEmailNuisanceOldColumns(alias)
}

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

func (s PublicreportNotifyEmailNuisanceOldSetter) 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.EmailAddress.IsValue() {
		vals = append(vals, "email_address")
	}
	return vals
}

func (s PublicreportNotifyEmailNuisanceOldSetter) Overwrite(t *PublicreportNotifyEmailNuisanceOld) {
	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.EmailAddress.IsValue() {
		t.EmailAddress = s.EmailAddress.MustGet()
	}
}

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

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

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

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

	return exprs
}

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

	return PublicreportNotifyEmailNuisanceOlds.Query(
		sm.Where(PublicreportNotifyEmailNuisanceOlds.Columns.NuisanceID.EQ(psql.Arg(NuisanceIDPK))),
		sm.Where(PublicreportNotifyEmailNuisanceOlds.Columns.EmailAddress.EQ(psql.Arg(EmailAddressPK))),
		sm.Columns(PublicreportNotifyEmailNuisanceOlds.Columns.Only(cols...)),
	).One(ctx, exec)
}

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

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

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

	return err
}

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

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

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

	return nil
}

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

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

	return err
}

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

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

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

			return err
		}))

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

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

			return err
		}))

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

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

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

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

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

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

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

	o.copyMatchingRows(o2...)

	return nil
}

// EmailAddressEmailContact starts a query for related objects on comms.email_contact
func (o *PublicreportNotifyEmailNuisanceOld) EmailAddressEmailContact(mods ...bob.Mod[*dialect.SelectQuery]) CommsEmailContactsQuery {
	return CommsEmailContacts.Query(append(mods,
		sm.Where(CommsEmailContacts.Columns.Address.EQ(psql.Arg(o.EmailAddress))),
	)...)
}

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

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

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

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

func attachPublicreportNotifyEmailNuisanceOldEmailAddressEmailContact0(ctx context.Context, exec bob.Executor, count int, publicreportNotifyEmailNuisanceOld0 *PublicreportNotifyEmailNuisanceOld, commsEmailContact1 *CommsEmailContact) (*PublicreportNotifyEmailNuisanceOld, error) {
	setter := &PublicreportNotifyEmailNuisanceOldSetter{
		EmailAddress: omit.From(commsEmailContact1.Address),
	}

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

	return publicreportNotifyEmailNuisanceOld0, nil
}

func (publicreportNotifyEmailNuisanceOld0 *PublicreportNotifyEmailNuisanceOld) InsertEmailAddressEmailContact(ctx context.Context, exec bob.Executor, related *CommsEmailContactSetter) error {
	var err error

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

	_, err = attachPublicreportNotifyEmailNuisanceOldEmailAddressEmailContact0(ctx, exec, 1, publicreportNotifyEmailNuisanceOld0, commsEmailContact1)
	if err != nil {
		return err
	}

	publicreportNotifyEmailNuisanceOld0.R.EmailAddressEmailContact = commsEmailContact1

	commsEmailContact1.R.EmailAddressNotifyEmailNuisanceOlds = append(commsEmailContact1.R.EmailAddressNotifyEmailNuisanceOlds, publicreportNotifyEmailNuisanceOld0)

	return nil
}

func (publicreportNotifyEmailNuisanceOld0 *PublicreportNotifyEmailNuisanceOld) AttachEmailAddressEmailContact(ctx context.Context, exec bob.Executor, commsEmailContact1 *CommsEmailContact) error {
	var err error

	_, err = attachPublicreportNotifyEmailNuisanceOldEmailAddressEmailContact0(ctx, exec, 1, publicreportNotifyEmailNuisanceOld0, commsEmailContact1)
	if err != nil {
		return err
	}

	publicreportNotifyEmailNuisanceOld0.R.EmailAddressEmailContact = commsEmailContact1

	commsEmailContact1.R.EmailAddressNotifyEmailNuisanceOlds = append(commsEmailContact1.R.EmailAddressNotifyEmailNuisanceOlds, publicreportNotifyEmailNuisanceOld0)

	return nil
}

func attachPublicreportNotifyEmailNuisanceOldNuisanceNuisanceOld0(ctx context.Context, exec bob.Executor, count int, publicreportNotifyEmailNuisanceOld0 *PublicreportNotifyEmailNuisanceOld, publicreportNuisanceOld1 *PublicreportNuisanceOld) (*PublicreportNotifyEmailNuisanceOld, error) {
	setter := &PublicreportNotifyEmailNuisanceOldSetter{
		NuisanceID: omit.From(publicreportNuisanceOld1.ID),
	}

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

	return publicreportNotifyEmailNuisanceOld0, nil
}

func (publicreportNotifyEmailNuisanceOld0 *PublicreportNotifyEmailNuisanceOld) 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 = attachPublicreportNotifyEmailNuisanceOldNuisanceNuisanceOld0(ctx, exec, 1, publicreportNotifyEmailNuisanceOld0, publicreportNuisanceOld1)
	if err != nil {
		return err
	}

	publicreportNotifyEmailNuisanceOld0.R.NuisanceNuisanceOld = publicreportNuisanceOld1

	publicreportNuisanceOld1.R.NuisanceNotifyEmailNuisanceOlds = append(publicreportNuisanceOld1.R.NuisanceNotifyEmailNuisanceOlds, publicreportNotifyEmailNuisanceOld0)

	return nil
}

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

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

	publicreportNotifyEmailNuisanceOld0.R.NuisanceNuisanceOld = publicreportNuisanceOld1

	publicreportNuisanceOld1.R.NuisanceNotifyEmailNuisanceOlds = append(publicreportNuisanceOld1.R.NuisanceNotifyEmailNuisanceOlds, publicreportNotifyEmailNuisanceOld0)

	return nil
}

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

func (publicreportNotifyEmailNuisanceOldWhere[Q]) AliasedAs(alias string) publicreportNotifyEmailNuisanceOldWhere[Q] {
	return buildPublicreportNotifyEmailNuisanceOldWhere[Q](buildPublicreportNotifyEmailNuisanceOldColumns(alias))
}

func buildPublicreportNotifyEmailNuisanceOldWhere[Q psql.Filterable](cols publicreportNotifyEmailNuisanceOldColumns) publicreportNotifyEmailNuisanceOldWhere[Q] {
	return publicreportNotifyEmailNuisanceOldWhere[Q]{
		Created:      psql.Where[Q, time.Time](cols.Created),
		Deleted:      psql.WhereNull[Q, time.Time](cols.Deleted),
		NuisanceID:   psql.Where[Q, int32](cols.NuisanceID),
		EmailAddress: psql.Where[Q, string](cols.EmailAddress),
	}
}

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

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

		o.R.EmailAddressEmailContact = rel

		if rel != nil {
			rel.R.EmailAddressNotifyEmailNuisanceOlds = PublicreportNotifyEmailNuisanceOldSlice{o}
		}
		return nil
	case "NuisanceNuisanceOld":
		rel, ok := retrieved.(*PublicreportNuisanceOld)
		if !ok {
			return fmt.Errorf("publicreportNotifyEmailNuisanceOld cannot load %T as %q", retrieved, name)
		}

		o.R.NuisanceNuisanceOld = rel

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

type publicreportNotifyEmailNuisanceOldPreloader struct {
	EmailAddressEmailContact func(...psql.PreloadOption) psql.Preloader
	NuisanceNuisanceOld      func(...psql.PreloadOption) psql.Preloader
}

func buildPublicreportNotifyEmailNuisanceOldPreloader() publicreportNotifyEmailNuisanceOldPreloader {
	return publicreportNotifyEmailNuisanceOldPreloader{
		EmailAddressEmailContact: func(opts ...psql.PreloadOption) psql.Preloader {
			return psql.Preload[*CommsEmailContact, CommsEmailContactSlice](psql.PreloadRel{
				Name: "EmailAddressEmailContact",
				Sides: []psql.PreloadSide{
					{
						From:        PublicreportNotifyEmailNuisanceOlds,
						To:          CommsEmailContacts,
						FromColumns: []string{"email_address"},
						ToColumns:   []string{"address"},
					},
				},
			}, CommsEmailContacts.Columns.Names(), opts...)
		},
		NuisanceNuisanceOld: func(opts ...psql.PreloadOption) psql.Preloader {
			return psql.Preload[*PublicreportNuisanceOld, PublicreportNuisanceOldSlice](psql.PreloadRel{
				Name: "NuisanceNuisanceOld",
				Sides: []psql.PreloadSide{
					{
						From:        PublicreportNotifyEmailNuisanceOlds,
						To:          PublicreportNuisanceOlds,
						FromColumns: []string{"nuisance_id"},
						ToColumns:   []string{"id"},
					},
				},
			}, PublicreportNuisanceOlds.Columns.Names(), opts...)
		},
	}
}

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

func buildPublicreportNotifyEmailNuisanceOldThenLoader[Q orm.Loadable]() publicreportNotifyEmailNuisanceOldThenLoader[Q] {
	type EmailAddressEmailContactLoadInterface interface {
		LoadEmailAddressEmailContact(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error
	}
	type NuisanceNuisanceOldLoadInterface interface {
		LoadNuisanceNuisanceOld(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error
	}

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

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

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

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

	related.R.EmailAddressNotifyEmailNuisanceOlds = PublicreportNotifyEmailNuisanceOldSlice{o}

	o.R.EmailAddressEmailContact = related
	return nil
}

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

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

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

		for _, rel := range commsEmailContacts {

			if !(o.EmailAddress == rel.Address) {
				continue
			}

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

			o.R.EmailAddressEmailContact = rel
			break
		}
	}

	return nil
}

// LoadNuisanceNuisanceOld loads the publicreportNotifyEmailNuisanceOld's NuisanceNuisanceOld into the .R struct
func (o *PublicreportNotifyEmailNuisanceOld) 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.NuisanceNotifyEmailNuisanceOlds = PublicreportNotifyEmailNuisanceOldSlice{o}

	o.R.NuisanceNuisanceOld = related
	return nil
}

// LoadNuisanceNuisanceOld loads the publicreportNotifyEmailNuisanceOld's NuisanceNuisanceOld into the .R struct
func (os PublicreportNotifyEmailNuisanceOldSlice) 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.NuisanceNotifyEmailNuisanceOlds = append(rel.R.NuisanceNotifyEmailNuisanceOlds, o)

			o.R.NuisanceNuisanceOld = rel
			break
		}
	}

	return nil
}
