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

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

	R publicreportNotifyEmailWaterOldR `db:"-" `
}

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

// PublicreportNotifyEmailWaterOlds contains methods to work with the notify_email_water_old table
var PublicreportNotifyEmailWaterOlds = psql.NewTablex[*PublicreportNotifyEmailWaterOld, PublicreportNotifyEmailWaterOldSlice, *PublicreportNotifyEmailWaterOldSetter]("publicreport", "notify_email_water_old", buildPublicreportNotifyEmailWaterOldColumns("publicreport.notify_email_water_old"))

// PublicreportNotifyEmailWaterOldsQuery is a query on the notify_email_water_old table
type PublicreportNotifyEmailWaterOldsQuery = *psql.ViewQuery[*PublicreportNotifyEmailWaterOld, PublicreportNotifyEmailWaterOldSlice]

// publicreportNotifyEmailWaterOldR is where relationships are stored.
type publicreportNotifyEmailWaterOldR struct {
	EmailAddressEmailContact *CommsEmailContact    // publicreport.notify_email_water_old.notify_email_pool_email_address_fkey
	WaterWaterOld            *PublicreportWaterOld // publicreport.notify_email_water_old.notify_email_pool_pool_id_fkey
}

func buildPublicreportNotifyEmailWaterOldColumns(alias string) publicreportNotifyEmailWaterOldColumns {
	return publicreportNotifyEmailWaterOldColumns{
		ColumnsExpr: expr.NewColumnsExpr(
			"created", "deleted", "water_id", "email_address",
		).WithParent("publicreport.notify_email_water_old"),
		tableAlias:   alias,
		Created:      psql.Quote(alias, "created"),
		Deleted:      psql.Quote(alias, "deleted"),
		WaterID:      psql.Quote(alias, "water_id"),
		EmailAddress: psql.Quote(alias, "email_address"),
	}
}

type publicreportNotifyEmailWaterOldColumns struct {
	expr.ColumnsExpr
	tableAlias   string
	Created      psql.Expression
	Deleted      psql.Expression
	WaterID      psql.Expression
	EmailAddress psql.Expression
}

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

func (publicreportNotifyEmailWaterOldColumns) AliasedAs(alias string) publicreportNotifyEmailWaterOldColumns {
	return buildPublicreportNotifyEmailWaterOldColumns(alias)
}

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

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

func (s PublicreportNotifyEmailWaterOldSetter) Overwrite(t *PublicreportNotifyEmailWaterOld) {
	if s.Created.IsValue() {
		t.Created = s.Created.MustGet()
	}
	if !s.Deleted.IsUnset() {
		t.Deleted = s.Deleted.MustGetNull()
	}
	if s.WaterID.IsValue() {
		t.WaterID = s.WaterID.MustGet()
	}
	if s.EmailAddress.IsValue() {
		t.EmailAddress = s.EmailAddress.MustGet()
	}
}

func (s *PublicreportNotifyEmailWaterOldSetter) Apply(q *dialect.InsertQuery) {
	q.AppendHooks(func(ctx context.Context, exec bob.Executor) (context.Context, error) {
		return PublicreportNotifyEmailWaterOlds.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.WaterID.IsValue() {
			vals[2] = psql.Arg(s.WaterID.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 PublicreportNotifyEmailWaterOldSetter) UpdateMod() bob.Mod[*dialect.UpdateQuery] {
	return um.Set(s.Expressions()...)
}

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

	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
}

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

	return PublicreportNotifyEmailWaterOlds.Query(
		sm.Where(PublicreportNotifyEmailWaterOlds.Columns.WaterID.EQ(psql.Arg(WaterIDPK))),
		sm.Where(PublicreportNotifyEmailWaterOlds.Columns.EmailAddress.EQ(psql.Arg(EmailAddressPK))),
		sm.Columns(PublicreportNotifyEmailWaterOlds.Columns.Only(cols...)),
	).One(ctx, exec)
}

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

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

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

	return err
}

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

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

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

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

	return err
}

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

	return psql.Group(psql.Quote("publicreport.notify_email_water_old", "water_id"), psql.Quote("publicreport.notify_email_water_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 PublicreportNotifyEmailWaterOldSlice) copyMatchingRows(from ...*PublicreportNotifyEmailWaterOld) {
	for i, old := range o {
		for _, new := range from {
			if new.WaterID != old.WaterID {
				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 PublicreportNotifyEmailWaterOldSlice) 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 PublicreportNotifyEmailWaterOlds.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 *PublicreportNotifyEmailWaterOld:
				o.copyMatchingRows(retrieved)
			case []*PublicreportNotifyEmailWaterOld:
				o.copyMatchingRows(retrieved...)
			case PublicreportNotifyEmailWaterOldSlice:
				o.copyMatchingRows(retrieved...)
			default:
				// If the retrieved value is not a PublicreportNotifyEmailWaterOld or a slice of PublicreportNotifyEmailWaterOld
				// then run the AfterUpdateHooks on the slice
				_, err = PublicreportNotifyEmailWaterOlds.AfterUpdateHooks.RunHooks(ctx, exec, o)
			}

			return err
		}))

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

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

			return err
		}))

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

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

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

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

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

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

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

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

// WaterWaterOld starts a query for related objects on publicreport.water_old
func (o *PublicreportNotifyEmailWaterOld) WaterWaterOld(mods ...bob.Mod[*dialect.SelectQuery]) PublicreportWaterOldsQuery {
	return PublicreportWaterOlds.Query(append(mods,
		sm.Where(PublicreportWaterOlds.Columns.ID.EQ(psql.Arg(o.WaterID))),
	)...)
}

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

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

func attachPublicreportNotifyEmailWaterOldEmailAddressEmailContact0(ctx context.Context, exec bob.Executor, count int, publicreportNotifyEmailWaterOld0 *PublicreportNotifyEmailWaterOld, commsEmailContact1 *CommsEmailContact) (*PublicreportNotifyEmailWaterOld, error) {
	setter := &PublicreportNotifyEmailWaterOldSetter{
		EmailAddress: omit.From(commsEmailContact1.Address),
	}

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

	return publicreportNotifyEmailWaterOld0, nil
}

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

	publicreportNotifyEmailWaterOld0.R.EmailAddressEmailContact = commsEmailContact1

	commsEmailContact1.R.EmailAddressNotifyEmailWaterOlds = append(commsEmailContact1.R.EmailAddressNotifyEmailWaterOlds, publicreportNotifyEmailWaterOld0)

	return nil
}

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

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

	publicreportNotifyEmailWaterOld0.R.EmailAddressEmailContact = commsEmailContact1

	commsEmailContact1.R.EmailAddressNotifyEmailWaterOlds = append(commsEmailContact1.R.EmailAddressNotifyEmailWaterOlds, publicreportNotifyEmailWaterOld0)

	return nil
}

func attachPublicreportNotifyEmailWaterOldWaterWaterOld0(ctx context.Context, exec bob.Executor, count int, publicreportNotifyEmailWaterOld0 *PublicreportNotifyEmailWaterOld, publicreportWaterOld1 *PublicreportWaterOld) (*PublicreportNotifyEmailWaterOld, error) {
	setter := &PublicreportNotifyEmailWaterOldSetter{
		WaterID: omit.From(publicreportWaterOld1.ID),
	}

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

	return publicreportNotifyEmailWaterOld0, nil
}

func (publicreportNotifyEmailWaterOld0 *PublicreportNotifyEmailWaterOld) InsertWaterWaterOld(ctx context.Context, exec bob.Executor, related *PublicreportWaterOldSetter) error {
	var err error

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

	_, err = attachPublicreportNotifyEmailWaterOldWaterWaterOld0(ctx, exec, 1, publicreportNotifyEmailWaterOld0, publicreportWaterOld1)
	if err != nil {
		return err
	}

	publicreportNotifyEmailWaterOld0.R.WaterWaterOld = publicreportWaterOld1

	publicreportWaterOld1.R.WaterNotifyEmailWaterOlds = append(publicreportWaterOld1.R.WaterNotifyEmailWaterOlds, publicreportNotifyEmailWaterOld0)

	return nil
}

func (publicreportNotifyEmailWaterOld0 *PublicreportNotifyEmailWaterOld) AttachWaterWaterOld(ctx context.Context, exec bob.Executor, publicreportWaterOld1 *PublicreportWaterOld) error {
	var err error

	_, err = attachPublicreportNotifyEmailWaterOldWaterWaterOld0(ctx, exec, 1, publicreportNotifyEmailWaterOld0, publicreportWaterOld1)
	if err != nil {
		return err
	}

	publicreportNotifyEmailWaterOld0.R.WaterWaterOld = publicreportWaterOld1

	publicreportWaterOld1.R.WaterNotifyEmailWaterOlds = append(publicreportWaterOld1.R.WaterNotifyEmailWaterOlds, publicreportNotifyEmailWaterOld0)

	return nil
}

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

func (publicreportNotifyEmailWaterOldWhere[Q]) AliasedAs(alias string) publicreportNotifyEmailWaterOldWhere[Q] {
	return buildPublicreportNotifyEmailWaterOldWhere[Q](buildPublicreportNotifyEmailWaterOldColumns(alias))
}

func buildPublicreportNotifyEmailWaterOldWhere[Q psql.Filterable](cols publicreportNotifyEmailWaterOldColumns) publicreportNotifyEmailWaterOldWhere[Q] {
	return publicreportNotifyEmailWaterOldWhere[Q]{
		Created:      psql.Where[Q, time.Time](cols.Created),
		Deleted:      psql.WhereNull[Q, time.Time](cols.Deleted),
		WaterID:      psql.Where[Q, int32](cols.WaterID),
		EmailAddress: psql.Where[Q, string](cols.EmailAddress),
	}
}

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

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

		o.R.EmailAddressEmailContact = rel

		if rel != nil {
			rel.R.EmailAddressNotifyEmailWaterOlds = PublicreportNotifyEmailWaterOldSlice{o}
		}
		return nil
	case "WaterWaterOld":
		rel, ok := retrieved.(*PublicreportWaterOld)
		if !ok {
			return fmt.Errorf("publicreportNotifyEmailWaterOld cannot load %T as %q", retrieved, name)
		}

		o.R.WaterWaterOld = rel

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

type publicreportNotifyEmailWaterOldPreloader struct {
	EmailAddressEmailContact func(...psql.PreloadOption) psql.Preloader
	WaterWaterOld            func(...psql.PreloadOption) psql.Preloader
}

func buildPublicreportNotifyEmailWaterOldPreloader() publicreportNotifyEmailWaterOldPreloader {
	return publicreportNotifyEmailWaterOldPreloader{
		EmailAddressEmailContact: func(opts ...psql.PreloadOption) psql.Preloader {
			return psql.Preload[*CommsEmailContact, CommsEmailContactSlice](psql.PreloadRel{
				Name: "EmailAddressEmailContact",
				Sides: []psql.PreloadSide{
					{
						From:        PublicreportNotifyEmailWaterOlds,
						To:          CommsEmailContacts,
						FromColumns: []string{"email_address"},
						ToColumns:   []string{"address"},
					},
				},
			}, CommsEmailContacts.Columns.Names(), opts...)
		},
		WaterWaterOld: func(opts ...psql.PreloadOption) psql.Preloader {
			return psql.Preload[*PublicreportWaterOld, PublicreportWaterOldSlice](psql.PreloadRel{
				Name: "WaterWaterOld",
				Sides: []psql.PreloadSide{
					{
						From:        PublicreportNotifyEmailWaterOlds,
						To:          PublicreportWaterOlds,
						FromColumns: []string{"water_id"},
						ToColumns:   []string{"id"},
					},
				},
			}, PublicreportWaterOlds.Columns.Names(), opts...)
		},
	}
}

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

func buildPublicreportNotifyEmailWaterOldThenLoader[Q orm.Loadable]() publicreportNotifyEmailWaterOldThenLoader[Q] {
	type EmailAddressEmailContactLoadInterface interface {
		LoadEmailAddressEmailContact(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error
	}
	type WaterWaterOldLoadInterface interface {
		LoadWaterWaterOld(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error
	}

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

// LoadEmailAddressEmailContact loads the publicreportNotifyEmailWaterOld's EmailAddressEmailContact into the .R struct
func (o *PublicreportNotifyEmailWaterOld) 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.EmailAddressNotifyEmailWaterOlds = PublicreportNotifyEmailWaterOldSlice{o}

	o.R.EmailAddressEmailContact = related
	return nil
}

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

			o.R.EmailAddressEmailContact = rel
			break
		}
	}

	return nil
}

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

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

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

	related.R.WaterNotifyEmailWaterOlds = PublicreportNotifyEmailWaterOldSlice{o}

	o.R.WaterWaterOld = related
	return nil
}

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

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

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

		for _, rel := range publicreportWaterOlds {

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

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

			o.R.WaterWaterOld = rel
			break
		}
	}

	return nil
}
