// 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"
	enums "source.gleipnir.technology/Gleipnir/nidus-sync/db/enums"
)

// CommsEmailLog is an object representing the database table.
type CommsEmailLog struct {
	ID             int32                       `db:"id,pk" `
	Created        time.Time                   `db:"created" `
	DeliveryStatus string                      `db:"delivery_status" `
	Destination    string                      `db:"destination" `
	PublicID       string                      `db:"public_id" `
	SentAt         null.Val[time.Time]         `db:"sent_at" `
	Source         string                      `db:"source" `
	Subject        string                      `db:"subject" `
	TemplateID     int32                       `db:"template_id" `
	TemplateData   pgtypes.HStore              `db:"template_data" `
	Type           enums.CommsMessagetypeemail `db:"type" `

	R commsEmailLogR `db:"-" `
}

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

// CommsEmailLogs contains methods to work with the email_log table
var CommsEmailLogs = psql.NewTablex[*CommsEmailLog, CommsEmailLogSlice, *CommsEmailLogSetter]("comms", "email_log", buildCommsEmailLogColumns("comms.email_log"))

// CommsEmailLogsQuery is a query on the email_log table
type CommsEmailLogsQuery = *psql.ViewQuery[*CommsEmailLog, CommsEmailLogSlice]

// commsEmailLogR is where relationships are stored.
type commsEmailLogR struct {
	DestinationEmailContact        *CommsEmailContact         // comms.email_log.email_log_destination_fkey
	TemplateEmailTemplate          *CommsEmailTemplate        // comms.email_log.email_log_template_id_fkey
	ResponseEmailLogCommunications CommunicationSlice         // communication.communication_response_email_log_id_fkey
	SourceEmailLogCommunications   CommunicationSlice         // communication.communication_source_email_log_id_fkey
	ReportLogs                     PublicreportReportLogSlice // publicreport.report_log.report_log_email_log_id_fkey
}

func buildCommsEmailLogColumns(alias string) commsEmailLogColumns {
	return commsEmailLogColumns{
		ColumnsExpr: expr.NewColumnsExpr(
			"id", "created", "delivery_status", "destination", "public_id", "sent_at", "source", "subject", "template_id", "template_data", "type",
		).WithParent("comms.email_log"),
		tableAlias:     alias,
		ID:             psql.Quote(alias, "id"),
		Created:        psql.Quote(alias, "created"),
		DeliveryStatus: psql.Quote(alias, "delivery_status"),
		Destination:    psql.Quote(alias, "destination"),
		PublicID:       psql.Quote(alias, "public_id"),
		SentAt:         psql.Quote(alias, "sent_at"),
		Source:         psql.Quote(alias, "source"),
		Subject:        psql.Quote(alias, "subject"),
		TemplateID:     psql.Quote(alias, "template_id"),
		TemplateData:   psql.Quote(alias, "template_data"),
		Type:           psql.Quote(alias, "type"),
	}
}

type commsEmailLogColumns struct {
	expr.ColumnsExpr
	tableAlias     string
	ID             psql.Expression
	Created        psql.Expression
	DeliveryStatus psql.Expression
	Destination    psql.Expression
	PublicID       psql.Expression
	SentAt         psql.Expression
	Source         psql.Expression
	Subject        psql.Expression
	TemplateID     psql.Expression
	TemplateData   psql.Expression
	Type           psql.Expression
}

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

func (commsEmailLogColumns) AliasedAs(alias string) commsEmailLogColumns {
	return buildCommsEmailLogColumns(alias)
}

// CommsEmailLogSetter is used for insert/upsert/update operations
// All values are optional, and do not have to be set
// Generated columns are not included
type CommsEmailLogSetter struct {
	ID             omit.Val[int32]                       `db:"id,pk" `
	Created        omit.Val[time.Time]                   `db:"created" `
	DeliveryStatus omit.Val[string]                      `db:"delivery_status" `
	Destination    omit.Val[string]                      `db:"destination" `
	PublicID       omit.Val[string]                      `db:"public_id" `
	SentAt         omitnull.Val[time.Time]               `db:"sent_at" `
	Source         omit.Val[string]                      `db:"source" `
	Subject        omit.Val[string]                      `db:"subject" `
	TemplateID     omit.Val[int32]                       `db:"template_id" `
	TemplateData   omit.Val[pgtypes.HStore]              `db:"template_data" `
	Type           omit.Val[enums.CommsMessagetypeemail] `db:"type" `
}

func (s CommsEmailLogSetter) SetColumns() []string {
	vals := make([]string, 0, 11)
	if s.ID.IsValue() {
		vals = append(vals, "id")
	}
	if s.Created.IsValue() {
		vals = append(vals, "created")
	}
	if s.DeliveryStatus.IsValue() {
		vals = append(vals, "delivery_status")
	}
	if s.Destination.IsValue() {
		vals = append(vals, "destination")
	}
	if s.PublicID.IsValue() {
		vals = append(vals, "public_id")
	}
	if !s.SentAt.IsUnset() {
		vals = append(vals, "sent_at")
	}
	if s.Source.IsValue() {
		vals = append(vals, "source")
	}
	if s.Subject.IsValue() {
		vals = append(vals, "subject")
	}
	if s.TemplateID.IsValue() {
		vals = append(vals, "template_id")
	}
	if s.TemplateData.IsValue() {
		vals = append(vals, "template_data")
	}
	if s.Type.IsValue() {
		vals = append(vals, "type")
	}
	return vals
}

func (s CommsEmailLogSetter) Overwrite(t *CommsEmailLog) {
	if s.ID.IsValue() {
		t.ID = s.ID.MustGet()
	}
	if s.Created.IsValue() {
		t.Created = s.Created.MustGet()
	}
	if s.DeliveryStatus.IsValue() {
		t.DeliveryStatus = s.DeliveryStatus.MustGet()
	}
	if s.Destination.IsValue() {
		t.Destination = s.Destination.MustGet()
	}
	if s.PublicID.IsValue() {
		t.PublicID = s.PublicID.MustGet()
	}
	if !s.SentAt.IsUnset() {
		t.SentAt = s.SentAt.MustGetNull()
	}
	if s.Source.IsValue() {
		t.Source = s.Source.MustGet()
	}
	if s.Subject.IsValue() {
		t.Subject = s.Subject.MustGet()
	}
	if s.TemplateID.IsValue() {
		t.TemplateID = s.TemplateID.MustGet()
	}
	if s.TemplateData.IsValue() {
		t.TemplateData = s.TemplateData.MustGet()
	}
	if s.Type.IsValue() {
		t.Type = s.Type.MustGet()
	}
}

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

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

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

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

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

		if !s.SentAt.IsUnset() {
			vals[5] = psql.Arg(s.SentAt.MustGetNull())
		} else {
			vals[5] = psql.Raw("DEFAULT")
		}

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

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

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

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

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

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

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

func (s CommsEmailLogSetter) Expressions(prefix ...string) []bob.Expression {
	exprs := make([]bob.Expression, 0, 11)

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

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

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

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

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

	if !s.SentAt.IsUnset() {
		exprs = append(exprs, expr.Join{Sep: " = ", Exprs: []bob.Expression{
			psql.Quote(append(prefix, "sent_at")...),
			psql.Arg(s.SentAt),
		}})
	}

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

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

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

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

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

	return exprs
}

// FindCommsEmailLog retrieves a single record by primary key
// If cols is empty Find will return all columns.
func FindCommsEmailLog(ctx context.Context, exec bob.Executor, IDPK int32, cols ...string) (*CommsEmailLog, error) {
	if len(cols) == 0 {
		return CommsEmailLogs.Query(
			sm.Where(CommsEmailLogs.Columns.ID.EQ(psql.Arg(IDPK))),
		).One(ctx, exec)
	}

	return CommsEmailLogs.Query(
		sm.Where(CommsEmailLogs.Columns.ID.EQ(psql.Arg(IDPK))),
		sm.Columns(CommsEmailLogs.Columns.Only(cols...)),
	).One(ctx, exec)
}

// CommsEmailLogExists checks the presence of a single record by primary key
func CommsEmailLogExists(ctx context.Context, exec bob.Executor, IDPK int32) (bool, error) {
	return CommsEmailLogs.Query(
		sm.Where(CommsEmailLogs.Columns.ID.EQ(psql.Arg(IDPK))),
	).Exists(ctx, exec)
}

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

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

	return err
}

// primaryKeyVals returns the primary key values of the CommsEmailLog
func (o *CommsEmailLog) primaryKeyVals() bob.Expression {
	return psql.Arg(o.ID)
}

func (o *CommsEmailLog) pkEQ() dialect.Expression {
	return psql.Quote("comms.email_log", "id").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 CommsEmailLog
func (o *CommsEmailLog) Update(ctx context.Context, exec bob.Executor, s *CommsEmailLogSetter) error {
	v, err := CommsEmailLogs.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 CommsEmailLog record with an executor
func (o *CommsEmailLog) Delete(ctx context.Context, exec bob.Executor) error {
	_, err := CommsEmailLogs.Delete(dm.Where(o.pkEQ())).Exec(ctx, exec)
	return err
}

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

	return nil
}

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

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

	return err
}

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

	return psql.Quote("comms.email_log", "id").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 CommsEmailLogSlice) copyMatchingRows(from ...*CommsEmailLog) {
	for i, old := range o {
		for _, new := range from {
			if new.ID != old.ID {
				continue
			}
			new.R = old.R
			o[i] = new
			break
		}
	}
}

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

			return err
		}))

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

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

			return err
		}))

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

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

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

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

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

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

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

	o.copyMatchingRows(o2...)

	return nil
}

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

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

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

// TemplateEmailTemplate starts a query for related objects on comms.email_template
func (o *CommsEmailLog) TemplateEmailTemplate(mods ...bob.Mod[*dialect.SelectQuery]) CommsEmailTemplatesQuery {
	return CommsEmailTemplates.Query(append(mods,
		sm.Where(CommsEmailTemplates.Columns.ID.EQ(psql.Arg(o.TemplateID))),
	)...)
}

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

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

// ResponseEmailLogCommunications starts a query for related objects on communication
func (o *CommsEmailLog) ResponseEmailLogCommunications(mods ...bob.Mod[*dialect.SelectQuery]) CommunicationsQuery {
	return Communications.Query(append(mods,
		sm.Where(Communications.Columns.ResponseEmailLogID.EQ(psql.Arg(o.ID))),
	)...)
}

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

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

// SourceEmailLogCommunications starts a query for related objects on communication
func (o *CommsEmailLog) SourceEmailLogCommunications(mods ...bob.Mod[*dialect.SelectQuery]) CommunicationsQuery {
	return Communications.Query(append(mods,
		sm.Where(Communications.Columns.SourceEmailLogID.EQ(psql.Arg(o.ID))),
	)...)
}

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

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

// ReportLogs starts a query for related objects on publicreport.report_log
func (o *CommsEmailLog) ReportLogs(mods ...bob.Mod[*dialect.SelectQuery]) PublicreportReportLogsQuery {
	return PublicreportReportLogs.Query(append(mods,
		sm.Where(PublicreportReportLogs.Columns.EmailLogID.EQ(psql.Arg(o.ID))),
	)...)
}

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

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

func attachCommsEmailLogDestinationEmailContact0(ctx context.Context, exec bob.Executor, count int, commsEmailLog0 *CommsEmailLog, commsEmailContact1 *CommsEmailContact) (*CommsEmailLog, error) {
	setter := &CommsEmailLogSetter{
		Destination: omit.From(commsEmailContact1.Address),
	}

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

	return commsEmailLog0, nil
}

func (commsEmailLog0 *CommsEmailLog) InsertDestinationEmailContact(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 = attachCommsEmailLogDestinationEmailContact0(ctx, exec, 1, commsEmailLog0, commsEmailContact1)
	if err != nil {
		return err
	}

	commsEmailLog0.R.DestinationEmailContact = commsEmailContact1

	commsEmailContact1.R.DestinationEmailLogs = append(commsEmailContact1.R.DestinationEmailLogs, commsEmailLog0)

	return nil
}

func (commsEmailLog0 *CommsEmailLog) AttachDestinationEmailContact(ctx context.Context, exec bob.Executor, commsEmailContact1 *CommsEmailContact) error {
	var err error

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

	commsEmailLog0.R.DestinationEmailContact = commsEmailContact1

	commsEmailContact1.R.DestinationEmailLogs = append(commsEmailContact1.R.DestinationEmailLogs, commsEmailLog0)

	return nil
}

func attachCommsEmailLogTemplateEmailTemplate0(ctx context.Context, exec bob.Executor, count int, commsEmailLog0 *CommsEmailLog, commsEmailTemplate1 *CommsEmailTemplate) (*CommsEmailLog, error) {
	setter := &CommsEmailLogSetter{
		TemplateID: omit.From(commsEmailTemplate1.ID),
	}

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

	return commsEmailLog0, nil
}

func (commsEmailLog0 *CommsEmailLog) InsertTemplateEmailTemplate(ctx context.Context, exec bob.Executor, related *CommsEmailTemplateSetter) error {
	var err error

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

	_, err = attachCommsEmailLogTemplateEmailTemplate0(ctx, exec, 1, commsEmailLog0, commsEmailTemplate1)
	if err != nil {
		return err
	}

	commsEmailLog0.R.TemplateEmailTemplate = commsEmailTemplate1

	commsEmailTemplate1.R.TemplateEmailLogs = append(commsEmailTemplate1.R.TemplateEmailLogs, commsEmailLog0)

	return nil
}

func (commsEmailLog0 *CommsEmailLog) AttachTemplateEmailTemplate(ctx context.Context, exec bob.Executor, commsEmailTemplate1 *CommsEmailTemplate) error {
	var err error

	_, err = attachCommsEmailLogTemplateEmailTemplate0(ctx, exec, 1, commsEmailLog0, commsEmailTemplate1)
	if err != nil {
		return err
	}

	commsEmailLog0.R.TemplateEmailTemplate = commsEmailTemplate1

	commsEmailTemplate1.R.TemplateEmailLogs = append(commsEmailTemplate1.R.TemplateEmailLogs, commsEmailLog0)

	return nil
}

func insertCommsEmailLogResponseEmailLogCommunications0(ctx context.Context, exec bob.Executor, communications1 []*CommunicationSetter, commsEmailLog0 *CommsEmailLog) (CommunicationSlice, error) {
	for i := range communications1 {
		communications1[i].ResponseEmailLogID = omitnull.From(commsEmailLog0.ID)
	}

	ret, err := Communications.Insert(bob.ToMods(communications1...)).All(ctx, exec)
	if err != nil {
		return ret, fmt.Errorf("insertCommsEmailLogResponseEmailLogCommunications0: %w", err)
	}

	return ret, nil
}

func attachCommsEmailLogResponseEmailLogCommunications0(ctx context.Context, exec bob.Executor, count int, communications1 CommunicationSlice, commsEmailLog0 *CommsEmailLog) (CommunicationSlice, error) {
	setter := &CommunicationSetter{
		ResponseEmailLogID: omitnull.From(commsEmailLog0.ID),
	}

	err := communications1.UpdateAll(ctx, exec, *setter)
	if err != nil {
		return nil, fmt.Errorf("attachCommsEmailLogResponseEmailLogCommunications0: %w", err)
	}

	return communications1, nil
}

func (commsEmailLog0 *CommsEmailLog) InsertResponseEmailLogCommunications(ctx context.Context, exec bob.Executor, related ...*CommunicationSetter) error {
	if len(related) == 0 {
		return nil
	}

	var err error

	communications1, err := insertCommsEmailLogResponseEmailLogCommunications0(ctx, exec, related, commsEmailLog0)
	if err != nil {
		return err
	}

	commsEmailLog0.R.ResponseEmailLogCommunications = append(commsEmailLog0.R.ResponseEmailLogCommunications, communications1...)

	for _, rel := range communications1 {
		rel.R.ResponseEmailLogEmailLog = commsEmailLog0
	}
	return nil
}

func (commsEmailLog0 *CommsEmailLog) AttachResponseEmailLogCommunications(ctx context.Context, exec bob.Executor, related ...*Communication) error {
	if len(related) == 0 {
		return nil
	}

	var err error
	communications1 := CommunicationSlice(related)

	_, err = attachCommsEmailLogResponseEmailLogCommunications0(ctx, exec, len(related), communications1, commsEmailLog0)
	if err != nil {
		return err
	}

	commsEmailLog0.R.ResponseEmailLogCommunications = append(commsEmailLog0.R.ResponseEmailLogCommunications, communications1...)

	for _, rel := range related {
		rel.R.ResponseEmailLogEmailLog = commsEmailLog0
	}

	return nil
}

func insertCommsEmailLogSourceEmailLogCommunications0(ctx context.Context, exec bob.Executor, communications1 []*CommunicationSetter, commsEmailLog0 *CommsEmailLog) (CommunicationSlice, error) {
	for i := range communications1 {
		communications1[i].SourceEmailLogID = omitnull.From(commsEmailLog0.ID)
	}

	ret, err := Communications.Insert(bob.ToMods(communications1...)).All(ctx, exec)
	if err != nil {
		return ret, fmt.Errorf("insertCommsEmailLogSourceEmailLogCommunications0: %w", err)
	}

	return ret, nil
}

func attachCommsEmailLogSourceEmailLogCommunications0(ctx context.Context, exec bob.Executor, count int, communications1 CommunicationSlice, commsEmailLog0 *CommsEmailLog) (CommunicationSlice, error) {
	setter := &CommunicationSetter{
		SourceEmailLogID: omitnull.From(commsEmailLog0.ID),
	}

	err := communications1.UpdateAll(ctx, exec, *setter)
	if err != nil {
		return nil, fmt.Errorf("attachCommsEmailLogSourceEmailLogCommunications0: %w", err)
	}

	return communications1, nil
}

func (commsEmailLog0 *CommsEmailLog) InsertSourceEmailLogCommunications(ctx context.Context, exec bob.Executor, related ...*CommunicationSetter) error {
	if len(related) == 0 {
		return nil
	}

	var err error

	communications1, err := insertCommsEmailLogSourceEmailLogCommunications0(ctx, exec, related, commsEmailLog0)
	if err != nil {
		return err
	}

	commsEmailLog0.R.SourceEmailLogCommunications = append(commsEmailLog0.R.SourceEmailLogCommunications, communications1...)

	for _, rel := range communications1 {
		rel.R.SourceEmailLogEmailLog = commsEmailLog0
	}
	return nil
}

func (commsEmailLog0 *CommsEmailLog) AttachSourceEmailLogCommunications(ctx context.Context, exec bob.Executor, related ...*Communication) error {
	if len(related) == 0 {
		return nil
	}

	var err error
	communications1 := CommunicationSlice(related)

	_, err = attachCommsEmailLogSourceEmailLogCommunications0(ctx, exec, len(related), communications1, commsEmailLog0)
	if err != nil {
		return err
	}

	commsEmailLog0.R.SourceEmailLogCommunications = append(commsEmailLog0.R.SourceEmailLogCommunications, communications1...)

	for _, rel := range related {
		rel.R.SourceEmailLogEmailLog = commsEmailLog0
	}

	return nil
}

func insertCommsEmailLogReportLogs0(ctx context.Context, exec bob.Executor, publicreportReportLogs1 []*PublicreportReportLogSetter, commsEmailLog0 *CommsEmailLog) (PublicreportReportLogSlice, error) {
	for i := range publicreportReportLogs1 {
		publicreportReportLogs1[i].EmailLogID = omitnull.From(commsEmailLog0.ID)
	}

	ret, err := PublicreportReportLogs.Insert(bob.ToMods(publicreportReportLogs1...)).All(ctx, exec)
	if err != nil {
		return ret, fmt.Errorf("insertCommsEmailLogReportLogs0: %w", err)
	}

	return ret, nil
}

func attachCommsEmailLogReportLogs0(ctx context.Context, exec bob.Executor, count int, publicreportReportLogs1 PublicreportReportLogSlice, commsEmailLog0 *CommsEmailLog) (PublicreportReportLogSlice, error) {
	setter := &PublicreportReportLogSetter{
		EmailLogID: omitnull.From(commsEmailLog0.ID),
	}

	err := publicreportReportLogs1.UpdateAll(ctx, exec, *setter)
	if err != nil {
		return nil, fmt.Errorf("attachCommsEmailLogReportLogs0: %w", err)
	}

	return publicreportReportLogs1, nil
}

func (commsEmailLog0 *CommsEmailLog) InsertReportLogs(ctx context.Context, exec bob.Executor, related ...*PublicreportReportLogSetter) error {
	if len(related) == 0 {
		return nil
	}

	var err error

	publicreportReportLogs1, err := insertCommsEmailLogReportLogs0(ctx, exec, related, commsEmailLog0)
	if err != nil {
		return err
	}

	commsEmailLog0.R.ReportLogs = append(commsEmailLog0.R.ReportLogs, publicreportReportLogs1...)

	for _, rel := range publicreportReportLogs1 {
		rel.R.EmailLog = commsEmailLog0
	}
	return nil
}

func (commsEmailLog0 *CommsEmailLog) AttachReportLogs(ctx context.Context, exec bob.Executor, related ...*PublicreportReportLog) error {
	if len(related) == 0 {
		return nil
	}

	var err error
	publicreportReportLogs1 := PublicreportReportLogSlice(related)

	_, err = attachCommsEmailLogReportLogs0(ctx, exec, len(related), publicreportReportLogs1, commsEmailLog0)
	if err != nil {
		return err
	}

	commsEmailLog0.R.ReportLogs = append(commsEmailLog0.R.ReportLogs, publicreportReportLogs1...)

	for _, rel := range related {
		rel.R.EmailLog = commsEmailLog0
	}

	return nil
}

type commsEmailLogWhere[Q psql.Filterable] struct {
	ID             psql.WhereMod[Q, int32]
	Created        psql.WhereMod[Q, time.Time]
	DeliveryStatus psql.WhereMod[Q, string]
	Destination    psql.WhereMod[Q, string]
	PublicID       psql.WhereMod[Q, string]
	SentAt         psql.WhereNullMod[Q, time.Time]
	Source         psql.WhereMod[Q, string]
	Subject        psql.WhereMod[Q, string]
	TemplateID     psql.WhereMod[Q, int32]
	TemplateData   psql.WhereMod[Q, pgtypes.HStore]
	Type           psql.WhereMod[Q, enums.CommsMessagetypeemail]
}

func (commsEmailLogWhere[Q]) AliasedAs(alias string) commsEmailLogWhere[Q] {
	return buildCommsEmailLogWhere[Q](buildCommsEmailLogColumns(alias))
}

func buildCommsEmailLogWhere[Q psql.Filterable](cols commsEmailLogColumns) commsEmailLogWhere[Q] {
	return commsEmailLogWhere[Q]{
		ID:             psql.Where[Q, int32](cols.ID),
		Created:        psql.Where[Q, time.Time](cols.Created),
		DeliveryStatus: psql.Where[Q, string](cols.DeliveryStatus),
		Destination:    psql.Where[Q, string](cols.Destination),
		PublicID:       psql.Where[Q, string](cols.PublicID),
		SentAt:         psql.WhereNull[Q, time.Time](cols.SentAt),
		Source:         psql.Where[Q, string](cols.Source),
		Subject:        psql.Where[Q, string](cols.Subject),
		TemplateID:     psql.Where[Q, int32](cols.TemplateID),
		TemplateData:   psql.Where[Q, pgtypes.HStore](cols.TemplateData),
		Type:           psql.Where[Q, enums.CommsMessagetypeemail](cols.Type),
	}
}

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

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

		o.R.DestinationEmailContact = rel

		if rel != nil {
			rel.R.DestinationEmailLogs = CommsEmailLogSlice{o}
		}
		return nil
	case "TemplateEmailTemplate":
		rel, ok := retrieved.(*CommsEmailTemplate)
		if !ok {
			return fmt.Errorf("commsEmailLog cannot load %T as %q", retrieved, name)
		}

		o.R.TemplateEmailTemplate = rel

		if rel != nil {
			rel.R.TemplateEmailLogs = CommsEmailLogSlice{o}
		}
		return nil
	case "ResponseEmailLogCommunications":
		rels, ok := retrieved.(CommunicationSlice)
		if !ok {
			return fmt.Errorf("commsEmailLog cannot load %T as %q", retrieved, name)
		}

		o.R.ResponseEmailLogCommunications = rels

		for _, rel := range rels {
			if rel != nil {
				rel.R.ResponseEmailLogEmailLog = o
			}
		}
		return nil
	case "SourceEmailLogCommunications":
		rels, ok := retrieved.(CommunicationSlice)
		if !ok {
			return fmt.Errorf("commsEmailLog cannot load %T as %q", retrieved, name)
		}

		o.R.SourceEmailLogCommunications = rels

		for _, rel := range rels {
			if rel != nil {
				rel.R.SourceEmailLogEmailLog = o
			}
		}
		return nil
	case "ReportLogs":
		rels, ok := retrieved.(PublicreportReportLogSlice)
		if !ok {
			return fmt.Errorf("commsEmailLog cannot load %T as %q", retrieved, name)
		}

		o.R.ReportLogs = rels

		for _, rel := range rels {
			if rel != nil {
				rel.R.EmailLog = o
			}
		}
		return nil
	default:
		return fmt.Errorf("commsEmailLog has no relationship %q", name)
	}
}

type commsEmailLogPreloader struct {
	DestinationEmailContact func(...psql.PreloadOption) psql.Preloader
	TemplateEmailTemplate   func(...psql.PreloadOption) psql.Preloader
}

func buildCommsEmailLogPreloader() commsEmailLogPreloader {
	return commsEmailLogPreloader{
		DestinationEmailContact: func(opts ...psql.PreloadOption) psql.Preloader {
			return psql.Preload[*CommsEmailContact, CommsEmailContactSlice](psql.PreloadRel{
				Name: "DestinationEmailContact",
				Sides: []psql.PreloadSide{
					{
						From:        CommsEmailLogs,
						To:          CommsEmailContacts,
						FromColumns: []string{"destination"},
						ToColumns:   []string{"address"},
					},
				},
			}, CommsEmailContacts.Columns.Names(), opts...)
		},
		TemplateEmailTemplate: func(opts ...psql.PreloadOption) psql.Preloader {
			return psql.Preload[*CommsEmailTemplate, CommsEmailTemplateSlice](psql.PreloadRel{
				Name: "TemplateEmailTemplate",
				Sides: []psql.PreloadSide{
					{
						From:        CommsEmailLogs,
						To:          CommsEmailTemplates,
						FromColumns: []string{"template_id"},
						ToColumns:   []string{"id"},
					},
				},
			}, CommsEmailTemplates.Columns.Names(), opts...)
		},
	}
}

type commsEmailLogThenLoader[Q orm.Loadable] struct {
	DestinationEmailContact        func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q]
	TemplateEmailTemplate          func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q]
	ResponseEmailLogCommunications func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q]
	SourceEmailLogCommunications   func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q]
	ReportLogs                     func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q]
}

func buildCommsEmailLogThenLoader[Q orm.Loadable]() commsEmailLogThenLoader[Q] {
	type DestinationEmailContactLoadInterface interface {
		LoadDestinationEmailContact(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error
	}
	type TemplateEmailTemplateLoadInterface interface {
		LoadTemplateEmailTemplate(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error
	}
	type ResponseEmailLogCommunicationsLoadInterface interface {
		LoadResponseEmailLogCommunications(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error
	}
	type SourceEmailLogCommunicationsLoadInterface interface {
		LoadSourceEmailLogCommunications(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error
	}
	type ReportLogsLoadInterface interface {
		LoadReportLogs(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error
	}

	return commsEmailLogThenLoader[Q]{
		DestinationEmailContact: thenLoadBuilder[Q](
			"DestinationEmailContact",
			func(ctx context.Context, exec bob.Executor, retrieved DestinationEmailContactLoadInterface, mods ...bob.Mod[*dialect.SelectQuery]) error {
				return retrieved.LoadDestinationEmailContact(ctx, exec, mods...)
			},
		),
		TemplateEmailTemplate: thenLoadBuilder[Q](
			"TemplateEmailTemplate",
			func(ctx context.Context, exec bob.Executor, retrieved TemplateEmailTemplateLoadInterface, mods ...bob.Mod[*dialect.SelectQuery]) error {
				return retrieved.LoadTemplateEmailTemplate(ctx, exec, mods...)
			},
		),
		ResponseEmailLogCommunications: thenLoadBuilder[Q](
			"ResponseEmailLogCommunications",
			func(ctx context.Context, exec bob.Executor, retrieved ResponseEmailLogCommunicationsLoadInterface, mods ...bob.Mod[*dialect.SelectQuery]) error {
				return retrieved.LoadResponseEmailLogCommunications(ctx, exec, mods...)
			},
		),
		SourceEmailLogCommunications: thenLoadBuilder[Q](
			"SourceEmailLogCommunications",
			func(ctx context.Context, exec bob.Executor, retrieved SourceEmailLogCommunicationsLoadInterface, mods ...bob.Mod[*dialect.SelectQuery]) error {
				return retrieved.LoadSourceEmailLogCommunications(ctx, exec, mods...)
			},
		),
		ReportLogs: thenLoadBuilder[Q](
			"ReportLogs",
			func(ctx context.Context, exec bob.Executor, retrieved ReportLogsLoadInterface, mods ...bob.Mod[*dialect.SelectQuery]) error {
				return retrieved.LoadReportLogs(ctx, exec, mods...)
			},
		),
	}
}

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

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

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

	related.R.DestinationEmailLogs = CommsEmailLogSlice{o}

	o.R.DestinationEmailContact = related
	return nil
}

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

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

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

		for _, rel := range commsEmailContacts {

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

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

			o.R.DestinationEmailContact = rel
			break
		}
	}

	return nil
}

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

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

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

	related.R.TemplateEmailLogs = CommsEmailLogSlice{o}

	o.R.TemplateEmailTemplate = related
	return nil
}

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

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

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

		for _, rel := range commsEmailTemplates {

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

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

			o.R.TemplateEmailTemplate = rel
			break
		}
	}

	return nil
}

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

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

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

	for _, rel := range related {
		rel.R.ResponseEmailLogEmailLog = o
	}

	o.R.ResponseEmailLogCommunications = related
	return nil
}

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

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

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

		o.R.ResponseEmailLogCommunications = nil
	}

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

		for _, rel := range communications {

			if !rel.ResponseEmailLogID.IsValue() {
				continue
			}
			if !(rel.ResponseEmailLogID.IsValue() && o.ID == rel.ResponseEmailLogID.MustGet()) {
				continue
			}

			rel.R.ResponseEmailLogEmailLog = o

			o.R.ResponseEmailLogCommunications = append(o.R.ResponseEmailLogCommunications, rel)
		}
	}

	return nil
}

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

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

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

	for _, rel := range related {
		rel.R.SourceEmailLogEmailLog = o
	}

	o.R.SourceEmailLogCommunications = related
	return nil
}

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

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

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

		o.R.SourceEmailLogCommunications = nil
	}

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

		for _, rel := range communications {

			if !rel.SourceEmailLogID.IsValue() {
				continue
			}
			if !(rel.SourceEmailLogID.IsValue() && o.ID == rel.SourceEmailLogID.MustGet()) {
				continue
			}

			rel.R.SourceEmailLogEmailLog = o

			o.R.SourceEmailLogCommunications = append(o.R.SourceEmailLogCommunications, rel)
		}
	}

	return nil
}

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

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

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

	for _, rel := range related {
		rel.R.EmailLog = o
	}

	o.R.ReportLogs = related
	return nil
}

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

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

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

		o.R.ReportLogs = nil
	}

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

		for _, rel := range publicreportReportLogs {

			if !rel.EmailLogID.IsValue() {
				continue
			}
			if !(rel.EmailLogID.IsValue() && o.ID == rel.EmailLogID.MustGet()) {
				continue
			}

			rel.R.EmailLog = o

			o.R.ReportLogs = append(o.R.ReportLogs, rel)
		}
	}

	return nil
}
