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

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

	R publicreportNotifyPhonePoolR `db:"-" `
}

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

// PublicreportNotifyPhonePools contains methods to work with the notify_phone_pool table
var PublicreportNotifyPhonePools = psql.NewTablex[*PublicreportNotifyPhonePool, PublicreportNotifyPhonePoolSlice, *PublicreportNotifyPhonePoolSetter]("publicreport", "notify_phone_pool", buildPublicreportNotifyPhonePoolColumns("publicreport.notify_phone_pool"))

// PublicreportNotifyPhonePoolsQuery is a query on the notify_phone_pool table
type PublicreportNotifyPhonePoolsQuery = *psql.ViewQuery[*PublicreportNotifyPhonePool, PublicreportNotifyPhonePoolSlice]

// publicreportNotifyPhonePoolR is where relationships are stored.
type publicreportNotifyPhonePoolR struct {
	PhoneE164Phone *CommsPhone       // publicreport.notify_phone_pool.notify_phone_pool_phone_e164_fkey
	Pool           *PublicreportPool // publicreport.notify_phone_pool.notify_phone_pool_pool_id_fkey
}

func buildPublicreportNotifyPhonePoolColumns(alias string) publicreportNotifyPhonePoolColumns {
	return publicreportNotifyPhonePoolColumns{
		ColumnsExpr: expr.NewColumnsExpr(
			"created", "deleted", "phone_e164", "pool_id",
		).WithParent("publicreport.notify_phone_pool"),
		tableAlias: alias,
		Created:    psql.Quote(alias, "created"),
		Deleted:    psql.Quote(alias, "deleted"),
		PhoneE164:  psql.Quote(alias, "phone_e164"),
		PoolID:     psql.Quote(alias, "pool_id"),
	}
}

type publicreportNotifyPhonePoolColumns struct {
	expr.ColumnsExpr
	tableAlias string
	Created    psql.Expression
	Deleted    psql.Expression
	PhoneE164  psql.Expression
	PoolID     psql.Expression
}

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

func (publicreportNotifyPhonePoolColumns) AliasedAs(alias string) publicreportNotifyPhonePoolColumns {
	return buildPublicreportNotifyPhonePoolColumns(alias)
}

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

func (s PublicreportNotifyPhonePoolSetter) 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.PhoneE164.IsValue() {
		vals = append(vals, "phone_e164")
	}
	if s.PoolID.IsValue() {
		vals = append(vals, "pool_id")
	}
	return vals
}

func (s PublicreportNotifyPhonePoolSetter) Overwrite(t *PublicreportNotifyPhonePool) {
	if s.Created.IsValue() {
		t.Created = s.Created.MustGet()
	}
	if !s.Deleted.IsUnset() {
		t.Deleted = s.Deleted.MustGetNull()
	}
	if s.PhoneE164.IsValue() {
		t.PhoneE164 = s.PhoneE164.MustGet()
	}
	if s.PoolID.IsValue() {
		t.PoolID = s.PoolID.MustGet()
	}
}

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

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

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

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

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

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

	return exprs
}

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

	return PublicreportNotifyPhonePools.Query(
		sm.Where(PublicreportNotifyPhonePools.Columns.PoolID.EQ(psql.Arg(PoolIDPK))),
		sm.Where(PublicreportNotifyPhonePools.Columns.PhoneE164.EQ(psql.Arg(PhoneE164PK))),
		sm.Columns(PublicreportNotifyPhonePools.Columns.Only(cols...)),
	).One(ctx, exec)
}

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

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

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

	return err
}

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

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

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

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

	return err
}

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

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

			return err
		}))

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

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

			return err
		}))

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

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

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

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

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

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

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

	o.copyMatchingRows(o2...)

	return nil
}

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

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

// Pool starts a query for related objects on publicreport.pool
func (o *PublicreportNotifyPhonePool) Pool(mods ...bob.Mod[*dialect.SelectQuery]) PublicreportPoolsQuery {
	return PublicreportPools.Query(append(mods,
		sm.Where(PublicreportPools.Columns.ID.EQ(psql.Arg(o.PoolID))),
	)...)
}

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

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

func attachPublicreportNotifyPhonePoolPhoneE164Phone0(ctx context.Context, exec bob.Executor, count int, publicreportNotifyPhonePool0 *PublicreportNotifyPhonePool, commsPhone1 *CommsPhone) (*PublicreportNotifyPhonePool, error) {
	setter := &PublicreportNotifyPhonePoolSetter{
		PhoneE164: omit.From(commsPhone1.E164),
	}

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

	return publicreportNotifyPhonePool0, nil
}

func (publicreportNotifyPhonePool0 *PublicreportNotifyPhonePool) 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 = attachPublicreportNotifyPhonePoolPhoneE164Phone0(ctx, exec, 1, publicreportNotifyPhonePool0, commsPhone1)
	if err != nil {
		return err
	}

	publicreportNotifyPhonePool0.R.PhoneE164Phone = commsPhone1

	commsPhone1.R.PhoneE164NotifyPhonePools = append(commsPhone1.R.PhoneE164NotifyPhonePools, publicreportNotifyPhonePool0)

	return nil
}

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

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

	publicreportNotifyPhonePool0.R.PhoneE164Phone = commsPhone1

	commsPhone1.R.PhoneE164NotifyPhonePools = append(commsPhone1.R.PhoneE164NotifyPhonePools, publicreportNotifyPhonePool0)

	return nil
}

func attachPublicreportNotifyPhonePoolPool0(ctx context.Context, exec bob.Executor, count int, publicreportNotifyPhonePool0 *PublicreportNotifyPhonePool, publicreportPool1 *PublicreportPool) (*PublicreportNotifyPhonePool, error) {
	setter := &PublicreportNotifyPhonePoolSetter{
		PoolID: omit.From(publicreportPool1.ID),
	}

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

	return publicreportNotifyPhonePool0, nil
}

func (publicreportNotifyPhonePool0 *PublicreportNotifyPhonePool) InsertPool(ctx context.Context, exec bob.Executor, related *PublicreportPoolSetter) error {
	var err error

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

	_, err = attachPublicreportNotifyPhonePoolPool0(ctx, exec, 1, publicreportNotifyPhonePool0, publicreportPool1)
	if err != nil {
		return err
	}

	publicreportNotifyPhonePool0.R.Pool = publicreportPool1

	publicreportPool1.R.NotifyPhonePools = append(publicreportPool1.R.NotifyPhonePools, publicreportNotifyPhonePool0)

	return nil
}

func (publicreportNotifyPhonePool0 *PublicreportNotifyPhonePool) AttachPool(ctx context.Context, exec bob.Executor, publicreportPool1 *PublicreportPool) error {
	var err error

	_, err = attachPublicreportNotifyPhonePoolPool0(ctx, exec, 1, publicreportNotifyPhonePool0, publicreportPool1)
	if err != nil {
		return err
	}

	publicreportNotifyPhonePool0.R.Pool = publicreportPool1

	publicreportPool1.R.NotifyPhonePools = append(publicreportPool1.R.NotifyPhonePools, publicreportNotifyPhonePool0)

	return nil
}

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

func (publicreportNotifyPhonePoolWhere[Q]) AliasedAs(alias string) publicreportNotifyPhonePoolWhere[Q] {
	return buildPublicreportNotifyPhonePoolWhere[Q](buildPublicreportNotifyPhonePoolColumns(alias))
}

func buildPublicreportNotifyPhonePoolWhere[Q psql.Filterable](cols publicreportNotifyPhonePoolColumns) publicreportNotifyPhonePoolWhere[Q] {
	return publicreportNotifyPhonePoolWhere[Q]{
		Created:   psql.Where[Q, time.Time](cols.Created),
		Deleted:   psql.WhereNull[Q, time.Time](cols.Deleted),
		PhoneE164: psql.Where[Q, string](cols.PhoneE164),
		PoolID:    psql.Where[Q, int32](cols.PoolID),
	}
}

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

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

		o.R.PhoneE164Phone = rel

		if rel != nil {
			rel.R.PhoneE164NotifyPhonePools = PublicreportNotifyPhonePoolSlice{o}
		}
		return nil
	case "Pool":
		rel, ok := retrieved.(*PublicreportPool)
		if !ok {
			return fmt.Errorf("publicreportNotifyPhonePool cannot load %T as %q", retrieved, name)
		}

		o.R.Pool = rel

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

type publicreportNotifyPhonePoolPreloader struct {
	PhoneE164Phone func(...psql.PreloadOption) psql.Preloader
	Pool           func(...psql.PreloadOption) psql.Preloader
}

func buildPublicreportNotifyPhonePoolPreloader() publicreportNotifyPhonePoolPreloader {
	return publicreportNotifyPhonePoolPreloader{
		PhoneE164Phone: func(opts ...psql.PreloadOption) psql.Preloader {
			return psql.Preload[*CommsPhone, CommsPhoneSlice](psql.PreloadRel{
				Name: "PhoneE164Phone",
				Sides: []psql.PreloadSide{
					{
						From:        PublicreportNotifyPhonePools,
						To:          CommsPhones,
						FromColumns: []string{"phone_e164"},
						ToColumns:   []string{"e164"},
					},
				},
			}, CommsPhones.Columns.Names(), opts...)
		},
		Pool: func(opts ...psql.PreloadOption) psql.Preloader {
			return psql.Preload[*PublicreportPool, PublicreportPoolSlice](psql.PreloadRel{
				Name: "Pool",
				Sides: []psql.PreloadSide{
					{
						From:        PublicreportNotifyPhonePools,
						To:          PublicreportPools,
						FromColumns: []string{"pool_id"},
						ToColumns:   []string{"id"},
					},
				},
			}, PublicreportPools.Columns.Names(), opts...)
		},
	}
}

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

func buildPublicreportNotifyPhonePoolThenLoader[Q orm.Loadable]() publicreportNotifyPhonePoolThenLoader[Q] {
	type PhoneE164PhoneLoadInterface interface {
		LoadPhoneE164Phone(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error
	}
	type PoolLoadInterface interface {
		LoadPool(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error
	}

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

// LoadPhoneE164Phone loads the publicreportNotifyPhonePool's PhoneE164Phone into the .R struct
func (o *PublicreportNotifyPhonePool) 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.PhoneE164NotifyPhonePools = PublicreportNotifyPhonePoolSlice{o}

	o.R.PhoneE164Phone = related
	return nil
}

// LoadPhoneE164Phone loads the publicreportNotifyPhonePool's PhoneE164Phone into the .R struct
func (os PublicreportNotifyPhonePoolSlice) 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.PhoneE164NotifyPhonePools = append(rel.R.PhoneE164NotifyPhonePools, o)

			o.R.PhoneE164Phone = rel
			break
		}
	}

	return nil
}

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

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

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

	related.R.NotifyPhonePools = PublicreportNotifyPhonePoolSlice{o}

	o.R.Pool = related
	return nil
}

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

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

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

		for _, rel := range publicreportPools {

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

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

			o.R.Pool = rel
			break
		}
	}

	return nil
}

type publicreportNotifyPhonePoolJoins[Q dialect.Joinable] struct {
	typ            string
	PhoneE164Phone modAs[Q, commsPhoneColumns]
	Pool           modAs[Q, publicreportPoolColumns]
}

func (j publicreportNotifyPhonePoolJoins[Q]) aliasedAs(alias string) publicreportNotifyPhonePoolJoins[Q] {
	return buildPublicreportNotifyPhonePoolJoins[Q](buildPublicreportNotifyPhonePoolColumns(alias), j.typ)
}

func buildPublicreportNotifyPhonePoolJoins[Q dialect.Joinable](cols publicreportNotifyPhonePoolColumns, typ string) publicreportNotifyPhonePoolJoins[Q] {
	return publicreportNotifyPhonePoolJoins[Q]{
		typ: typ,
		PhoneE164Phone: modAs[Q, commsPhoneColumns]{
			c: CommsPhones.Columns,
			f: func(to commsPhoneColumns) bob.Mod[Q] {
				mods := make(mods.QueryMods[Q], 0, 1)

				{
					mods = append(mods, dialect.Join[Q](typ, CommsPhones.Name().As(to.Alias())).On(
						to.E164.EQ(cols.PhoneE164),
					))
				}

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

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

				return mods
			},
		},
	}
}
