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

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

	R publicreportNotifyEmailR `db:"-" `
}

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

// PublicreportNotifyEmails contains methods to work with the notify_email table
var PublicreportNotifyEmails = psql.NewTablex[*PublicreportNotifyEmail, PublicreportNotifyEmailSlice, *PublicreportNotifyEmailSetter]("publicreport", "notify_email", buildPublicreportNotifyEmailColumns("publicreport.notify_email"))

// PublicreportNotifyEmailsQuery is a query on the notify_email table
type PublicreportNotifyEmailsQuery = *psql.ViewQuery[*PublicreportNotifyEmail, PublicreportNotifyEmailSlice]

// publicreportNotifyEmailR is where relationships are stored.
type publicreportNotifyEmailR struct {
	EmailAddressEmailContact *CommsEmailContact  // publicreport.notify_email.notify_email_email_address_fkey
	Report                   *PublicreportReport // publicreport.notify_email.notify_email_report_id_fkey
}

func buildPublicreportNotifyEmailColumns(alias string) publicreportNotifyEmailColumns {
	return publicreportNotifyEmailColumns{
		ColumnsExpr: expr.NewColumnsExpr(
			"created", "deleted", "email_address", "report_id",
		).WithParent("publicreport.notify_email"),
		tableAlias:   alias,
		Created:      psql.Quote(alias, "created"),
		Deleted:      psql.Quote(alias, "deleted"),
		EmailAddress: psql.Quote(alias, "email_address"),
		ReportID:     psql.Quote(alias, "report_id"),
	}
}

type publicreportNotifyEmailColumns struct {
	expr.ColumnsExpr
	tableAlias   string
	Created      psql.Expression
	Deleted      psql.Expression
	EmailAddress psql.Expression
	ReportID     psql.Expression
}

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

func (publicreportNotifyEmailColumns) AliasedAs(alias string) publicreportNotifyEmailColumns {
	return buildPublicreportNotifyEmailColumns(alias)
}

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

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

func (s PublicreportNotifyEmailSetter) Overwrite(t *PublicreportNotifyEmail) {
	if s.Created.IsValue() {
		t.Created = s.Created.MustGet()
	}
	if !s.Deleted.IsUnset() {
		t.Deleted = s.Deleted.MustGetNull()
	}
	if s.EmailAddress.IsValue() {
		t.EmailAddress = s.EmailAddress.MustGet()
	}
	if s.ReportID.IsValue() {
		t.ReportID = s.ReportID.MustGet()
	}
}

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

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

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

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

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

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

	return exprs
}

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

	return PublicreportNotifyEmails.Query(
		sm.Where(PublicreportNotifyEmails.Columns.ReportID.EQ(psql.Arg(ReportIDPK))),
		sm.Where(PublicreportNotifyEmails.Columns.EmailAddress.EQ(psql.Arg(EmailAddressPK))),
		sm.Columns(PublicreportNotifyEmails.Columns.Only(cols...)),
	).One(ctx, exec)
}

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

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

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

	return err
}

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

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

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

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

	return err
}

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

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

			return err
		}))

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

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

			return err
		}))

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

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

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

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

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

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

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

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

// Report starts a query for related objects on publicreport.report
func (o *PublicreportNotifyEmail) Report(mods ...bob.Mod[*dialect.SelectQuery]) PublicreportReportsQuery {
	return PublicreportReports.Query(append(mods,
		sm.Where(PublicreportReports.Columns.ID.EQ(psql.Arg(o.ReportID))),
	)...)
}

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

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

func attachPublicreportNotifyEmailEmailAddressEmailContact0(ctx context.Context, exec bob.Executor, count int, publicreportNotifyEmail0 *PublicreportNotifyEmail, commsEmailContact1 *CommsEmailContact) (*PublicreportNotifyEmail, error) {
	setter := &PublicreportNotifyEmailSetter{
		EmailAddress: omit.From(commsEmailContact1.Address),
	}

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

	return publicreportNotifyEmail0, nil
}

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

	publicreportNotifyEmail0.R.EmailAddressEmailContact = commsEmailContact1

	commsEmailContact1.R.EmailAddressNotifyEmails = append(commsEmailContact1.R.EmailAddressNotifyEmails, publicreportNotifyEmail0)

	return nil
}

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

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

	publicreportNotifyEmail0.R.EmailAddressEmailContact = commsEmailContact1

	commsEmailContact1.R.EmailAddressNotifyEmails = append(commsEmailContact1.R.EmailAddressNotifyEmails, publicreportNotifyEmail0)

	return nil
}

func attachPublicreportNotifyEmailReport0(ctx context.Context, exec bob.Executor, count int, publicreportNotifyEmail0 *PublicreportNotifyEmail, publicreportReport1 *PublicreportReport) (*PublicreportNotifyEmail, error) {
	setter := &PublicreportNotifyEmailSetter{
		ReportID: omit.From(publicreportReport1.ID),
	}

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

	return publicreportNotifyEmail0, nil
}

func (publicreportNotifyEmail0 *PublicreportNotifyEmail) InsertReport(ctx context.Context, exec bob.Executor, related *PublicreportReportSetter) error {
	var err error

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

	_, err = attachPublicreportNotifyEmailReport0(ctx, exec, 1, publicreportNotifyEmail0, publicreportReport1)
	if err != nil {
		return err
	}

	publicreportNotifyEmail0.R.Report = publicreportReport1

	publicreportReport1.R.NotifyEmails = append(publicreportReport1.R.NotifyEmails, publicreportNotifyEmail0)

	return nil
}

func (publicreportNotifyEmail0 *PublicreportNotifyEmail) AttachReport(ctx context.Context, exec bob.Executor, publicreportReport1 *PublicreportReport) error {
	var err error

	_, err = attachPublicreportNotifyEmailReport0(ctx, exec, 1, publicreportNotifyEmail0, publicreportReport1)
	if err != nil {
		return err
	}

	publicreportNotifyEmail0.R.Report = publicreportReport1

	publicreportReport1.R.NotifyEmails = append(publicreportReport1.R.NotifyEmails, publicreportNotifyEmail0)

	return nil
}

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

func (publicreportNotifyEmailWhere[Q]) AliasedAs(alias string) publicreportNotifyEmailWhere[Q] {
	return buildPublicreportNotifyEmailWhere[Q](buildPublicreportNotifyEmailColumns(alias))
}

func buildPublicreportNotifyEmailWhere[Q psql.Filterable](cols publicreportNotifyEmailColumns) publicreportNotifyEmailWhere[Q] {
	return publicreportNotifyEmailWhere[Q]{
		Created:      psql.Where[Q, time.Time](cols.Created),
		Deleted:      psql.WhereNull[Q, time.Time](cols.Deleted),
		EmailAddress: psql.Where[Q, string](cols.EmailAddress),
		ReportID:     psql.Where[Q, int32](cols.ReportID),
	}
}

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

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

		o.R.EmailAddressEmailContact = rel

		if rel != nil {
			rel.R.EmailAddressNotifyEmails = PublicreportNotifyEmailSlice{o}
		}
		return nil
	case "Report":
		rel, ok := retrieved.(*PublicreportReport)
		if !ok {
			return fmt.Errorf("publicreportNotifyEmail cannot load %T as %q", retrieved, name)
		}

		o.R.Report = rel

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

type publicreportNotifyEmailPreloader struct {
	EmailAddressEmailContact func(...psql.PreloadOption) psql.Preloader
	Report                   func(...psql.PreloadOption) psql.Preloader
}

func buildPublicreportNotifyEmailPreloader() publicreportNotifyEmailPreloader {
	return publicreportNotifyEmailPreloader{
		EmailAddressEmailContact: func(opts ...psql.PreloadOption) psql.Preloader {
			return psql.Preload[*CommsEmailContact, CommsEmailContactSlice](psql.PreloadRel{
				Name: "EmailAddressEmailContact",
				Sides: []psql.PreloadSide{
					{
						From:        PublicreportNotifyEmails,
						To:          CommsEmailContacts,
						FromColumns: []string{"email_address"},
						ToColumns:   []string{"address"},
					},
				},
			}, CommsEmailContacts.Columns.Names(), opts...)
		},
		Report: func(opts ...psql.PreloadOption) psql.Preloader {
			return psql.Preload[*PublicreportReport, PublicreportReportSlice](psql.PreloadRel{
				Name: "Report",
				Sides: []psql.PreloadSide{
					{
						From:        PublicreportNotifyEmails,
						To:          PublicreportReports,
						FromColumns: []string{"report_id"},
						ToColumns:   []string{"id"},
					},
				},
			}, PublicreportReports.Columns.Names(), opts...)
		},
	}
}

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

func buildPublicreportNotifyEmailThenLoader[Q orm.Loadable]() publicreportNotifyEmailThenLoader[Q] {
	type EmailAddressEmailContactLoadInterface interface {
		LoadEmailAddressEmailContact(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error
	}
	type ReportLoadInterface interface {
		LoadReport(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error
	}

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

// LoadEmailAddressEmailContact loads the publicreportNotifyEmail's EmailAddressEmailContact into the .R struct
func (o *PublicreportNotifyEmail) 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.EmailAddressNotifyEmails = PublicreportNotifyEmailSlice{o}

	o.R.EmailAddressEmailContact = related
	return nil
}

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

			o.R.EmailAddressEmailContact = rel
			break
		}
	}

	return nil
}

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

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

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

	related.R.NotifyEmails = PublicreportNotifyEmailSlice{o}

	o.R.Report = related
	return nil
}

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

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

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

		for _, rel := range publicreportReports {

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

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

			o.R.Report = rel
			break
		}
	}

	return nil
}
