// 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"
	"github.com/aarondl/opt/null"
	"github.com/aarondl/opt/omit"
	"github.com/aarondl/opt/omitnull"
)

// PublicreportNotifyEmailNuisance is an object representing the database table.
type PublicreportNotifyEmailNuisance 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 publicreportNotifyEmailNuisanceR `db:"-" `
}

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

// PublicreportNotifyEmailNuisances contains methods to work with the notify_email_nuisance table
var PublicreportNotifyEmailNuisances = psql.NewTablex[*PublicreportNotifyEmailNuisance, PublicreportNotifyEmailNuisanceSlice, *PublicreportNotifyEmailNuisanceSetter]("publicreport", "notify_email_nuisance", buildPublicreportNotifyEmailNuisanceColumns("publicreport.notify_email_nuisance"))

// PublicreportNotifyEmailNuisancesQuery is a query on the notify_email_nuisance table
type PublicreportNotifyEmailNuisancesQuery = *psql.ViewQuery[*PublicreportNotifyEmailNuisance, PublicreportNotifyEmailNuisanceSlice]

// publicreportNotifyEmailNuisanceR is where relationships are stored.
type publicreportNotifyEmailNuisanceR struct {
	EmailAddressEmailContact *CommsEmailContact    // publicreport.notify_email_nuisance.notify_email_nuisance_email_address_fkey
	Nuisance                 *PublicreportNuisance // publicreport.notify_email_nuisance.notify_email_nuisance_nuisance_id_fkey
}

func buildPublicreportNotifyEmailNuisanceColumns(alias string) publicreportNotifyEmailNuisanceColumns {
	return publicreportNotifyEmailNuisanceColumns{
		ColumnsExpr: expr.NewColumnsExpr(
			"created", "deleted", "nuisance_id", "email_address",
		).WithParent("publicreport.notify_email_nuisance"),
		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 publicreportNotifyEmailNuisanceColumns struct {
	expr.ColumnsExpr
	tableAlias   string
	Created      psql.Expression
	Deleted      psql.Expression
	NuisanceID   psql.Expression
	EmailAddress psql.Expression
}

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

func (publicreportNotifyEmailNuisanceColumns) AliasedAs(alias string) publicreportNotifyEmailNuisanceColumns {
	return buildPublicreportNotifyEmailNuisanceColumns(alias)
}

// PublicreportNotifyEmailNuisanceSetter is used for insert/upsert/update operations
// All values are optional, and do not have to be set
// Generated columns are not included
type PublicreportNotifyEmailNuisanceSetter 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 PublicreportNotifyEmailNuisanceSetter) 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 PublicreportNotifyEmailNuisanceSetter) Overwrite(t *PublicreportNotifyEmailNuisance) {
	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 *PublicreportNotifyEmailNuisanceSetter) Apply(q *dialect.InsertQuery) {
	q.AppendHooks(func(ctx context.Context, exec bob.Executor) (context.Context, error) {
		return PublicreportNotifyEmailNuisances.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 PublicreportNotifyEmailNuisanceSetter) UpdateMod() bob.Mod[*dialect.UpdateQuery] {
	return um.Set(s.Expressions()...)
}

func (s PublicreportNotifyEmailNuisanceSetter) 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
}

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

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

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

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

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

	return err
}

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

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

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

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

	return err
}

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

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

			return err
		}))

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

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

			return err
		}))

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

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

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

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

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

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

	o2, err := PublicreportNotifyEmailNuisances.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 *PublicreportNotifyEmailNuisance) EmailAddressEmailContact(mods ...bob.Mod[*dialect.SelectQuery]) CommsEmailContactsQuery {
	return CommsEmailContacts.Query(append(mods,
		sm.Where(CommsEmailContacts.Columns.Address.EQ(psql.Arg(o.EmailAddress))),
	)...)
}

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

// Nuisance starts a query for related objects on publicreport.nuisance
func (o *PublicreportNotifyEmailNuisance) Nuisance(mods ...bob.Mod[*dialect.SelectQuery]) PublicreportNuisancesQuery {
	return PublicreportNuisances.Query(append(mods,
		sm.Where(PublicreportNuisances.Columns.ID.EQ(psql.Arg(o.NuisanceID))),
	)...)
}

func (os PublicreportNotifyEmailNuisanceSlice) Nuisance(mods ...bob.Mod[*dialect.SelectQuery]) PublicreportNuisancesQuery {
	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 PublicreportNuisances.Query(append(mods,
		sm.Where(psql.Group(PublicreportNuisances.Columns.ID).OP("IN", PKArgExpr)),
	)...)
}

func attachPublicreportNotifyEmailNuisanceEmailAddressEmailContact0(ctx context.Context, exec bob.Executor, count int, publicreportNotifyEmailNuisance0 *PublicreportNotifyEmailNuisance, commsEmailContact1 *CommsEmailContact) (*PublicreportNotifyEmailNuisance, error) {
	setter := &PublicreportNotifyEmailNuisanceSetter{
		EmailAddress: omit.From(commsEmailContact1.Address),
	}

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

	return publicreportNotifyEmailNuisance0, nil
}

func (publicreportNotifyEmailNuisance0 *PublicreportNotifyEmailNuisance) 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 = attachPublicreportNotifyEmailNuisanceEmailAddressEmailContact0(ctx, exec, 1, publicreportNotifyEmailNuisance0, commsEmailContact1)
	if err != nil {
		return err
	}

	publicreportNotifyEmailNuisance0.R.EmailAddressEmailContact = commsEmailContact1

	commsEmailContact1.R.EmailAddressNotifyEmailNuisances = append(commsEmailContact1.R.EmailAddressNotifyEmailNuisances, publicreportNotifyEmailNuisance0)

	return nil
}

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

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

	publicreportNotifyEmailNuisance0.R.EmailAddressEmailContact = commsEmailContact1

	commsEmailContact1.R.EmailAddressNotifyEmailNuisances = append(commsEmailContact1.R.EmailAddressNotifyEmailNuisances, publicreportNotifyEmailNuisance0)

	return nil
}

func attachPublicreportNotifyEmailNuisanceNuisance0(ctx context.Context, exec bob.Executor, count int, publicreportNotifyEmailNuisance0 *PublicreportNotifyEmailNuisance, publicreportNuisance1 *PublicreportNuisance) (*PublicreportNotifyEmailNuisance, error) {
	setter := &PublicreportNotifyEmailNuisanceSetter{
		NuisanceID: omit.From(publicreportNuisance1.ID),
	}

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

	return publicreportNotifyEmailNuisance0, nil
}

func (publicreportNotifyEmailNuisance0 *PublicreportNotifyEmailNuisance) InsertNuisance(ctx context.Context, exec bob.Executor, related *PublicreportNuisanceSetter) error {
	var err error

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

	_, err = attachPublicreportNotifyEmailNuisanceNuisance0(ctx, exec, 1, publicreportNotifyEmailNuisance0, publicreportNuisance1)
	if err != nil {
		return err
	}

	publicreportNotifyEmailNuisance0.R.Nuisance = publicreportNuisance1

	publicreportNuisance1.R.NotifyEmailNuisances = append(publicreportNuisance1.R.NotifyEmailNuisances, publicreportNotifyEmailNuisance0)

	return nil
}

func (publicreportNotifyEmailNuisance0 *PublicreportNotifyEmailNuisance) AttachNuisance(ctx context.Context, exec bob.Executor, publicreportNuisance1 *PublicreportNuisance) error {
	var err error

	_, err = attachPublicreportNotifyEmailNuisanceNuisance0(ctx, exec, 1, publicreportNotifyEmailNuisance0, publicreportNuisance1)
	if err != nil {
		return err
	}

	publicreportNotifyEmailNuisance0.R.Nuisance = publicreportNuisance1

	publicreportNuisance1.R.NotifyEmailNuisances = append(publicreportNuisance1.R.NotifyEmailNuisances, publicreportNotifyEmailNuisance0)

	return nil
}

type publicreportNotifyEmailNuisanceWhere[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 (publicreportNotifyEmailNuisanceWhere[Q]) AliasedAs(alias string) publicreportNotifyEmailNuisanceWhere[Q] {
	return buildPublicreportNotifyEmailNuisanceWhere[Q](buildPublicreportNotifyEmailNuisanceColumns(alias))
}

func buildPublicreportNotifyEmailNuisanceWhere[Q psql.Filterable](cols publicreportNotifyEmailNuisanceColumns) publicreportNotifyEmailNuisanceWhere[Q] {
	return publicreportNotifyEmailNuisanceWhere[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 *PublicreportNotifyEmailNuisance) Preload(name string, retrieved any) error {
	if o == nil {
		return nil
	}

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

		o.R.EmailAddressEmailContact = rel

		if rel != nil {
			rel.R.EmailAddressNotifyEmailNuisances = PublicreportNotifyEmailNuisanceSlice{o}
		}
		return nil
	case "Nuisance":
		rel, ok := retrieved.(*PublicreportNuisance)
		if !ok {
			return fmt.Errorf("publicreportNotifyEmailNuisance cannot load %T as %q", retrieved, name)
		}

		o.R.Nuisance = rel

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

type publicreportNotifyEmailNuisancePreloader struct {
	EmailAddressEmailContact func(...psql.PreloadOption) psql.Preloader
	Nuisance                 func(...psql.PreloadOption) psql.Preloader
}

func buildPublicreportNotifyEmailNuisancePreloader() publicreportNotifyEmailNuisancePreloader {
	return publicreportNotifyEmailNuisancePreloader{
		EmailAddressEmailContact: func(opts ...psql.PreloadOption) psql.Preloader {
			return psql.Preload[*CommsEmailContact, CommsEmailContactSlice](psql.PreloadRel{
				Name: "EmailAddressEmailContact",
				Sides: []psql.PreloadSide{
					{
						From:        PublicreportNotifyEmailNuisances,
						To:          CommsEmailContacts,
						FromColumns: []string{"email_address"},
						ToColumns:   []string{"address"},
					},
				},
			}, CommsEmailContacts.Columns.Names(), opts...)
		},
		Nuisance: func(opts ...psql.PreloadOption) psql.Preloader {
			return psql.Preload[*PublicreportNuisance, PublicreportNuisanceSlice](psql.PreloadRel{
				Name: "Nuisance",
				Sides: []psql.PreloadSide{
					{
						From:        PublicreportNotifyEmailNuisances,
						To:          PublicreportNuisances,
						FromColumns: []string{"nuisance_id"},
						ToColumns:   []string{"id"},
					},
				},
			}, PublicreportNuisances.Columns.Names(), opts...)
		},
	}
}

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

func buildPublicreportNotifyEmailNuisanceThenLoader[Q orm.Loadable]() publicreportNotifyEmailNuisanceThenLoader[Q] {
	type EmailAddressEmailContactLoadInterface interface {
		LoadEmailAddressEmailContact(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error
	}
	type NuisanceLoadInterface interface {
		LoadNuisance(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error
	}

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

// LoadEmailAddressEmailContact loads the publicreportNotifyEmailNuisance's EmailAddressEmailContact into the .R struct
func (o *PublicreportNotifyEmailNuisance) 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.EmailAddressNotifyEmailNuisances = PublicreportNotifyEmailNuisanceSlice{o}

	o.R.EmailAddressEmailContact = related
	return nil
}

// LoadEmailAddressEmailContact loads the publicreportNotifyEmailNuisance's EmailAddressEmailContact into the .R struct
func (os PublicreportNotifyEmailNuisanceSlice) 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.EmailAddressNotifyEmailNuisances = append(rel.R.EmailAddressNotifyEmailNuisances, o)

			o.R.EmailAddressEmailContact = rel
			break
		}
	}

	return nil
}

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

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

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

	related.R.NotifyEmailNuisances = PublicreportNotifyEmailNuisanceSlice{o}

	o.R.Nuisance = related
	return nil
}

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

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

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

		for _, rel := range publicreportNuisances {

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

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

			o.R.Nuisance = rel
			break
		}
	}

	return nil
}

type publicreportNotifyEmailNuisanceJoins[Q dialect.Joinable] struct {
	typ                      string
	EmailAddressEmailContact modAs[Q, commsEmailContactColumns]
	Nuisance                 modAs[Q, publicreportNuisanceColumns]
}

func (j publicreportNotifyEmailNuisanceJoins[Q]) aliasedAs(alias string) publicreportNotifyEmailNuisanceJoins[Q] {
	return buildPublicreportNotifyEmailNuisanceJoins[Q](buildPublicreportNotifyEmailNuisanceColumns(alias), j.typ)
}

func buildPublicreportNotifyEmailNuisanceJoins[Q dialect.Joinable](cols publicreportNotifyEmailNuisanceColumns, typ string) publicreportNotifyEmailNuisanceJoins[Q] {
	return publicreportNotifyEmailNuisanceJoins[Q]{
		typ: typ,
		EmailAddressEmailContact: modAs[Q, commsEmailContactColumns]{
			c: CommsEmailContacts.Columns,
			f: func(to commsEmailContactColumns) bob.Mod[Q] {
				mods := make(mods.QueryMods[Q], 0, 1)

				{
					mods = append(mods, dialect.Join[Q](typ, CommsEmailContacts.Name().As(to.Alias())).On(
						to.Address.EQ(cols.EmailAddress),
					))
				}

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

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

				return mods
			},
		},
	}
}
