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

// CommsTextLog is an object representing the database table.
type CommsTextLog struct {
	Content        string                `db:"content" `
	Created        time.Time             `db:"created" `
	Destination    string                `db:"destination" `
	ID             int32                 `db:"id,pk" `
	IsWelcome      bool                  `db:"is_welcome" `
	Origin         enums.CommsTextorigin `db:"origin" `
	Source         string                `db:"source" `
	TwilioSid      null.Val[string]      `db:"twilio_sid" `
	TwilioStatus   string                `db:"twilio_status" `
	IsVisibleToLLM bool                  `db:"is_visible_to_llm" `

	R commsTextLogR `db:"-" `
}

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

// CommsTextLogs contains methods to work with the text_log table
var CommsTextLogs = psql.NewTablex[*CommsTextLog, CommsTextLogSlice, *CommsTextLogSetter]("comms", "text_log", buildCommsTextLogColumns("comms.text_log"))

// CommsTextLogsQuery is a query on the text_log table
type CommsTextLogsQuery = *psql.ViewQuery[*CommsTextLog, CommsTextLogSlice]

// commsTextLogR is where relationships are stored.
type commsTextLogR struct {
	DestinationPhone              *CommsPhone                // comms.text_log.text_log_destination_fkey
	SourcePhone                   *CommsPhone                // comms.text_log.text_log_source_fkey
	ResponseTextLogCommunications CommunicationSlice         // communication.communication_response_text_log_id_fkey
	SourceTextLogCommunications   CommunicationSlice         // communication.communication_source_text_log_id_fkey
	ReportLogs                    PublicreportReportLogSlice // publicreport.report_log.report_log_text_log_id_fkey
	ReportTexts                   ReportTextSlice            // report_text.report_text_text_log_id_fkey
}

func buildCommsTextLogColumns(alias string) commsTextLogColumns {
	return commsTextLogColumns{
		ColumnsExpr: expr.NewColumnsExpr(
			"content", "created", "destination", "id", "is_welcome", "origin", "source", "twilio_sid", "twilio_status", "is_visible_to_llm",
		).WithParent("comms.text_log"),
		tableAlias:     alias,
		Content:        psql.Quote(alias, "content"),
		Created:        psql.Quote(alias, "created"),
		Destination:    psql.Quote(alias, "destination"),
		ID:             psql.Quote(alias, "id"),
		IsWelcome:      psql.Quote(alias, "is_welcome"),
		Origin:         psql.Quote(alias, "origin"),
		Source:         psql.Quote(alias, "source"),
		TwilioSid:      psql.Quote(alias, "twilio_sid"),
		TwilioStatus:   psql.Quote(alias, "twilio_status"),
		IsVisibleToLLM: psql.Quote(alias, "is_visible_to_llm"),
	}
}

type commsTextLogColumns struct {
	expr.ColumnsExpr
	tableAlias     string
	Content        psql.Expression
	Created        psql.Expression
	Destination    psql.Expression
	ID             psql.Expression
	IsWelcome      psql.Expression
	Origin         psql.Expression
	Source         psql.Expression
	TwilioSid      psql.Expression
	TwilioStatus   psql.Expression
	IsVisibleToLLM psql.Expression
}

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

func (commsTextLogColumns) AliasedAs(alias string) commsTextLogColumns {
	return buildCommsTextLogColumns(alias)
}

// CommsTextLogSetter is used for insert/upsert/update operations
// All values are optional, and do not have to be set
// Generated columns are not included
type CommsTextLogSetter struct {
	Content        omit.Val[string]                `db:"content" `
	Created        omit.Val[time.Time]             `db:"created" `
	Destination    omit.Val[string]                `db:"destination" `
	ID             omit.Val[int32]                 `db:"id,pk" `
	IsWelcome      omit.Val[bool]                  `db:"is_welcome" `
	Origin         omit.Val[enums.CommsTextorigin] `db:"origin" `
	Source         omit.Val[string]                `db:"source" `
	TwilioSid      omitnull.Val[string]            `db:"twilio_sid" `
	TwilioStatus   omit.Val[string]                `db:"twilio_status" `
	IsVisibleToLLM omit.Val[bool]                  `db:"is_visible_to_llm" `
}

func (s CommsTextLogSetter) SetColumns() []string {
	vals := make([]string, 0, 10)
	if s.Content.IsValue() {
		vals = append(vals, "content")
	}
	if s.Created.IsValue() {
		vals = append(vals, "created")
	}
	if s.Destination.IsValue() {
		vals = append(vals, "destination")
	}
	if s.ID.IsValue() {
		vals = append(vals, "id")
	}
	if s.IsWelcome.IsValue() {
		vals = append(vals, "is_welcome")
	}
	if s.Origin.IsValue() {
		vals = append(vals, "origin")
	}
	if s.Source.IsValue() {
		vals = append(vals, "source")
	}
	if !s.TwilioSid.IsUnset() {
		vals = append(vals, "twilio_sid")
	}
	if s.TwilioStatus.IsValue() {
		vals = append(vals, "twilio_status")
	}
	if s.IsVisibleToLLM.IsValue() {
		vals = append(vals, "is_visible_to_llm")
	}
	return vals
}

func (s CommsTextLogSetter) Overwrite(t *CommsTextLog) {
	if s.Content.IsValue() {
		t.Content = s.Content.MustGet()
	}
	if s.Created.IsValue() {
		t.Created = s.Created.MustGet()
	}
	if s.Destination.IsValue() {
		t.Destination = s.Destination.MustGet()
	}
	if s.ID.IsValue() {
		t.ID = s.ID.MustGet()
	}
	if s.IsWelcome.IsValue() {
		t.IsWelcome = s.IsWelcome.MustGet()
	}
	if s.Origin.IsValue() {
		t.Origin = s.Origin.MustGet()
	}
	if s.Source.IsValue() {
		t.Source = s.Source.MustGet()
	}
	if !s.TwilioSid.IsUnset() {
		t.TwilioSid = s.TwilioSid.MustGetNull()
	}
	if s.TwilioStatus.IsValue() {
		t.TwilioStatus = s.TwilioStatus.MustGet()
	}
	if s.IsVisibleToLLM.IsValue() {
		t.IsVisibleToLLM = s.IsVisibleToLLM.MustGet()
	}
}

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

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

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

		if s.Origin.IsValue() {
			vals[5] = psql.Arg(s.Origin.MustGet())
		} 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.TwilioSid.IsUnset() {
			vals[7] = psql.Arg(s.TwilioSid.MustGetNull())
		} else {
			vals[7] = psql.Raw("DEFAULT")
		}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

	return exprs
}

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

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

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

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

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

	return err
}

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

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

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

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

	return err
}

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

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

			return err
		}))

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

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

			return err
		}))

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

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

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

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

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

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

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

	o.copyMatchingRows(o2...)

	return nil
}

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

func (os CommsTextLogSlice) DestinationPhone(mods ...bob.Mod[*dialect.SelectQuery]) CommsPhonesQuery {
	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 CommsPhones.Query(append(mods,
		sm.Where(psql.Group(CommsPhones.Columns.E164).OP("IN", PKArgExpr)),
	)...)
}

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

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

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

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

func (os CommsTextLogSlice) ResponseTextLogCommunications(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.ResponseTextLogID).OP("IN", PKArgExpr)),
	)...)
}

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

func (os CommsTextLogSlice) SourceTextLogCommunications(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.SourceTextLogID).OP("IN", PKArgExpr)),
	)...)
}

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

func (os CommsTextLogSlice) 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.TextLogID).OP("IN", PKArgExpr)),
	)...)
}

// ReportTexts starts a query for related objects on report_text
func (o *CommsTextLog) ReportTexts(mods ...bob.Mod[*dialect.SelectQuery]) ReportTextsQuery {
	return ReportTexts.Query(append(mods,
		sm.Where(ReportTexts.Columns.TextLogID.EQ(psql.Arg(o.ID))),
	)...)
}

func (os CommsTextLogSlice) ReportTexts(mods ...bob.Mod[*dialect.SelectQuery]) ReportTextsQuery {
	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 ReportTexts.Query(append(mods,
		sm.Where(psql.Group(ReportTexts.Columns.TextLogID).OP("IN", PKArgExpr)),
	)...)
}

func attachCommsTextLogDestinationPhone0(ctx context.Context, exec bob.Executor, count int, commsTextLog0 *CommsTextLog, commsPhone1 *CommsPhone) (*CommsTextLog, error) {
	setter := &CommsTextLogSetter{
		Destination: omit.From(commsPhone1.E164),
	}

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

	return commsTextLog0, nil
}

func (commsTextLog0 *CommsTextLog) InsertDestinationPhone(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 = attachCommsTextLogDestinationPhone0(ctx, exec, 1, commsTextLog0, commsPhone1)
	if err != nil {
		return err
	}

	commsTextLog0.R.DestinationPhone = commsPhone1

	commsPhone1.R.DestinationTextLogs = append(commsPhone1.R.DestinationTextLogs, commsTextLog0)

	return nil
}

func (commsTextLog0 *CommsTextLog) AttachDestinationPhone(ctx context.Context, exec bob.Executor, commsPhone1 *CommsPhone) error {
	var err error

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

	commsTextLog0.R.DestinationPhone = commsPhone1

	commsPhone1.R.DestinationTextLogs = append(commsPhone1.R.DestinationTextLogs, commsTextLog0)

	return nil
}

func attachCommsTextLogSourcePhone0(ctx context.Context, exec bob.Executor, count int, commsTextLog0 *CommsTextLog, commsPhone1 *CommsPhone) (*CommsTextLog, error) {
	setter := &CommsTextLogSetter{
		Source: omit.From(commsPhone1.E164),
	}

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

	return commsTextLog0, nil
}

func (commsTextLog0 *CommsTextLog) InsertSourcePhone(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 = attachCommsTextLogSourcePhone0(ctx, exec, 1, commsTextLog0, commsPhone1)
	if err != nil {
		return err
	}

	commsTextLog0.R.SourcePhone = commsPhone1

	commsPhone1.R.SourceTextLogs = append(commsPhone1.R.SourceTextLogs, commsTextLog0)

	return nil
}

func (commsTextLog0 *CommsTextLog) AttachSourcePhone(ctx context.Context, exec bob.Executor, commsPhone1 *CommsPhone) error {
	var err error

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

	commsTextLog0.R.SourcePhone = commsPhone1

	commsPhone1.R.SourceTextLogs = append(commsPhone1.R.SourceTextLogs, commsTextLog0)

	return nil
}

func insertCommsTextLogResponseTextLogCommunications0(ctx context.Context, exec bob.Executor, communications1 []*CommunicationSetter, commsTextLog0 *CommsTextLog) (CommunicationSlice, error) {
	for i := range communications1 {
		communications1[i].ResponseTextLogID = omitnull.From(commsTextLog0.ID)
	}

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

	return ret, nil
}

func attachCommsTextLogResponseTextLogCommunications0(ctx context.Context, exec bob.Executor, count int, communications1 CommunicationSlice, commsTextLog0 *CommsTextLog) (CommunicationSlice, error) {
	setter := &CommunicationSetter{
		ResponseTextLogID: omitnull.From(commsTextLog0.ID),
	}

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

	return communications1, nil
}

func (commsTextLog0 *CommsTextLog) InsertResponseTextLogCommunications(ctx context.Context, exec bob.Executor, related ...*CommunicationSetter) error {
	if len(related) == 0 {
		return nil
	}

	var err error

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

	commsTextLog0.R.ResponseTextLogCommunications = append(commsTextLog0.R.ResponseTextLogCommunications, communications1...)

	for _, rel := range communications1 {
		rel.R.ResponseTextLogTextLog = commsTextLog0
	}
	return nil
}

func (commsTextLog0 *CommsTextLog) AttachResponseTextLogCommunications(ctx context.Context, exec bob.Executor, related ...*Communication) error {
	if len(related) == 0 {
		return nil
	}

	var err error
	communications1 := CommunicationSlice(related)

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

	commsTextLog0.R.ResponseTextLogCommunications = append(commsTextLog0.R.ResponseTextLogCommunications, communications1...)

	for _, rel := range related {
		rel.R.ResponseTextLogTextLog = commsTextLog0
	}

	return nil
}

func insertCommsTextLogSourceTextLogCommunications0(ctx context.Context, exec bob.Executor, communications1 []*CommunicationSetter, commsTextLog0 *CommsTextLog) (CommunicationSlice, error) {
	for i := range communications1 {
		communications1[i].SourceTextLogID = omitnull.From(commsTextLog0.ID)
	}

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

	return ret, nil
}

func attachCommsTextLogSourceTextLogCommunications0(ctx context.Context, exec bob.Executor, count int, communications1 CommunicationSlice, commsTextLog0 *CommsTextLog) (CommunicationSlice, error) {
	setter := &CommunicationSetter{
		SourceTextLogID: omitnull.From(commsTextLog0.ID),
	}

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

	return communications1, nil
}

func (commsTextLog0 *CommsTextLog) InsertSourceTextLogCommunications(ctx context.Context, exec bob.Executor, related ...*CommunicationSetter) error {
	if len(related) == 0 {
		return nil
	}

	var err error

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

	commsTextLog0.R.SourceTextLogCommunications = append(commsTextLog0.R.SourceTextLogCommunications, communications1...)

	for _, rel := range communications1 {
		rel.R.SourceTextLogTextLog = commsTextLog0
	}
	return nil
}

func (commsTextLog0 *CommsTextLog) AttachSourceTextLogCommunications(ctx context.Context, exec bob.Executor, related ...*Communication) error {
	if len(related) == 0 {
		return nil
	}

	var err error
	communications1 := CommunicationSlice(related)

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

	commsTextLog0.R.SourceTextLogCommunications = append(commsTextLog0.R.SourceTextLogCommunications, communications1...)

	for _, rel := range related {
		rel.R.SourceTextLogTextLog = commsTextLog0
	}

	return nil
}

func insertCommsTextLogReportLogs0(ctx context.Context, exec bob.Executor, publicreportReportLogs1 []*PublicreportReportLogSetter, commsTextLog0 *CommsTextLog) (PublicreportReportLogSlice, error) {
	for i := range publicreportReportLogs1 {
		publicreportReportLogs1[i].TextLogID = omitnull.From(commsTextLog0.ID)
	}

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

	return ret, nil
}

func attachCommsTextLogReportLogs0(ctx context.Context, exec bob.Executor, count int, publicreportReportLogs1 PublicreportReportLogSlice, commsTextLog0 *CommsTextLog) (PublicreportReportLogSlice, error) {
	setter := &PublicreportReportLogSetter{
		TextLogID: omitnull.From(commsTextLog0.ID),
	}

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

	return publicreportReportLogs1, nil
}

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

	var err error

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

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

	for _, rel := range publicreportReportLogs1 {
		rel.R.TextLog = commsTextLog0
	}
	return nil
}

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

	var err error
	publicreportReportLogs1 := PublicreportReportLogSlice(related)

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

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

	for _, rel := range related {
		rel.R.TextLog = commsTextLog0
	}

	return nil
}

func insertCommsTextLogReportTexts0(ctx context.Context, exec bob.Executor, reportTexts1 []*ReportTextSetter, commsTextLog0 *CommsTextLog) (ReportTextSlice, error) {
	for i := range reportTexts1 {
		reportTexts1[i].TextLogID = omit.From(commsTextLog0.ID)
	}

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

	return ret, nil
}

func attachCommsTextLogReportTexts0(ctx context.Context, exec bob.Executor, count int, reportTexts1 ReportTextSlice, commsTextLog0 *CommsTextLog) (ReportTextSlice, error) {
	setter := &ReportTextSetter{
		TextLogID: omit.From(commsTextLog0.ID),
	}

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

	return reportTexts1, nil
}

func (commsTextLog0 *CommsTextLog) InsertReportTexts(ctx context.Context, exec bob.Executor, related ...*ReportTextSetter) error {
	if len(related) == 0 {
		return nil
	}

	var err error

	reportTexts1, err := insertCommsTextLogReportTexts0(ctx, exec, related, commsTextLog0)
	if err != nil {
		return err
	}

	commsTextLog0.R.ReportTexts = append(commsTextLog0.R.ReportTexts, reportTexts1...)

	for _, rel := range reportTexts1 {
		rel.R.TextLog = commsTextLog0
	}
	return nil
}

func (commsTextLog0 *CommsTextLog) AttachReportTexts(ctx context.Context, exec bob.Executor, related ...*ReportText) error {
	if len(related) == 0 {
		return nil
	}

	var err error
	reportTexts1 := ReportTextSlice(related)

	_, err = attachCommsTextLogReportTexts0(ctx, exec, len(related), reportTexts1, commsTextLog0)
	if err != nil {
		return err
	}

	commsTextLog0.R.ReportTexts = append(commsTextLog0.R.ReportTexts, reportTexts1...)

	for _, rel := range related {
		rel.R.TextLog = commsTextLog0
	}

	return nil
}

type commsTextLogWhere[Q psql.Filterable] struct {
	Content        psql.WhereMod[Q, string]
	Created        psql.WhereMod[Q, time.Time]
	Destination    psql.WhereMod[Q, string]
	ID             psql.WhereMod[Q, int32]
	IsWelcome      psql.WhereMod[Q, bool]
	Origin         psql.WhereMod[Q, enums.CommsTextorigin]
	Source         psql.WhereMod[Q, string]
	TwilioSid      psql.WhereNullMod[Q, string]
	TwilioStatus   psql.WhereMod[Q, string]
	IsVisibleToLLM psql.WhereMod[Q, bool]
}

func (commsTextLogWhere[Q]) AliasedAs(alias string) commsTextLogWhere[Q] {
	return buildCommsTextLogWhere[Q](buildCommsTextLogColumns(alias))
}

func buildCommsTextLogWhere[Q psql.Filterable](cols commsTextLogColumns) commsTextLogWhere[Q] {
	return commsTextLogWhere[Q]{
		Content:        psql.Where[Q, string](cols.Content),
		Created:        psql.Where[Q, time.Time](cols.Created),
		Destination:    psql.Where[Q, string](cols.Destination),
		ID:             psql.Where[Q, int32](cols.ID),
		IsWelcome:      psql.Where[Q, bool](cols.IsWelcome),
		Origin:         psql.Where[Q, enums.CommsTextorigin](cols.Origin),
		Source:         psql.Where[Q, string](cols.Source),
		TwilioSid:      psql.WhereNull[Q, string](cols.TwilioSid),
		TwilioStatus:   psql.Where[Q, string](cols.TwilioStatus),
		IsVisibleToLLM: psql.Where[Q, bool](cols.IsVisibleToLLM),
	}
}

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

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

		o.R.DestinationPhone = rel

		if rel != nil {
			rel.R.DestinationTextLogs = CommsTextLogSlice{o}
		}
		return nil
	case "SourcePhone":
		rel, ok := retrieved.(*CommsPhone)
		if !ok {
			return fmt.Errorf("commsTextLog cannot load %T as %q", retrieved, name)
		}

		o.R.SourcePhone = rel

		if rel != nil {
			rel.R.SourceTextLogs = CommsTextLogSlice{o}
		}
		return nil
	case "ResponseTextLogCommunications":
		rels, ok := retrieved.(CommunicationSlice)
		if !ok {
			return fmt.Errorf("commsTextLog cannot load %T as %q", retrieved, name)
		}

		o.R.ResponseTextLogCommunications = rels

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

		o.R.SourceTextLogCommunications = rels

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

		o.R.ReportLogs = rels

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

		o.R.ReportTexts = rels

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

type commsTextLogPreloader struct {
	DestinationPhone func(...psql.PreloadOption) psql.Preloader
	SourcePhone      func(...psql.PreloadOption) psql.Preloader
}

func buildCommsTextLogPreloader() commsTextLogPreloader {
	return commsTextLogPreloader{
		DestinationPhone: func(opts ...psql.PreloadOption) psql.Preloader {
			return psql.Preload[*CommsPhone, CommsPhoneSlice](psql.PreloadRel{
				Name: "DestinationPhone",
				Sides: []psql.PreloadSide{
					{
						From:        CommsTextLogs,
						To:          CommsPhones,
						FromColumns: []string{"destination"},
						ToColumns:   []string{"e164"},
					},
				},
			}, CommsPhones.Columns.Names(), opts...)
		},
		SourcePhone: func(opts ...psql.PreloadOption) psql.Preloader {
			return psql.Preload[*CommsPhone, CommsPhoneSlice](psql.PreloadRel{
				Name: "SourcePhone",
				Sides: []psql.PreloadSide{
					{
						From:        CommsTextLogs,
						To:          CommsPhones,
						FromColumns: []string{"source"},
						ToColumns:   []string{"e164"},
					},
				},
			}, CommsPhones.Columns.Names(), opts...)
		},
	}
}

type commsTextLogThenLoader[Q orm.Loadable] struct {
	DestinationPhone              func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q]
	SourcePhone                   func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q]
	ResponseTextLogCommunications func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q]
	SourceTextLogCommunications   func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q]
	ReportLogs                    func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q]
	ReportTexts                   func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q]
}

func buildCommsTextLogThenLoader[Q orm.Loadable]() commsTextLogThenLoader[Q] {
	type DestinationPhoneLoadInterface interface {
		LoadDestinationPhone(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error
	}
	type SourcePhoneLoadInterface interface {
		LoadSourcePhone(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error
	}
	type ResponseTextLogCommunicationsLoadInterface interface {
		LoadResponseTextLogCommunications(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error
	}
	type SourceTextLogCommunicationsLoadInterface interface {
		LoadSourceTextLogCommunications(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error
	}
	type ReportLogsLoadInterface interface {
		LoadReportLogs(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error
	}
	type ReportTextsLoadInterface interface {
		LoadReportTexts(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error
	}

	return commsTextLogThenLoader[Q]{
		DestinationPhone: thenLoadBuilder[Q](
			"DestinationPhone",
			func(ctx context.Context, exec bob.Executor, retrieved DestinationPhoneLoadInterface, mods ...bob.Mod[*dialect.SelectQuery]) error {
				return retrieved.LoadDestinationPhone(ctx, exec, mods...)
			},
		),
		SourcePhone: thenLoadBuilder[Q](
			"SourcePhone",
			func(ctx context.Context, exec bob.Executor, retrieved SourcePhoneLoadInterface, mods ...bob.Mod[*dialect.SelectQuery]) error {
				return retrieved.LoadSourcePhone(ctx, exec, mods...)
			},
		),
		ResponseTextLogCommunications: thenLoadBuilder[Q](
			"ResponseTextLogCommunications",
			func(ctx context.Context, exec bob.Executor, retrieved ResponseTextLogCommunicationsLoadInterface, mods ...bob.Mod[*dialect.SelectQuery]) error {
				return retrieved.LoadResponseTextLogCommunications(ctx, exec, mods...)
			},
		),
		SourceTextLogCommunications: thenLoadBuilder[Q](
			"SourceTextLogCommunications",
			func(ctx context.Context, exec bob.Executor, retrieved SourceTextLogCommunicationsLoadInterface, mods ...bob.Mod[*dialect.SelectQuery]) error {
				return retrieved.LoadSourceTextLogCommunications(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...)
			},
		),
		ReportTexts: thenLoadBuilder[Q](
			"ReportTexts",
			func(ctx context.Context, exec bob.Executor, retrieved ReportTextsLoadInterface, mods ...bob.Mod[*dialect.SelectQuery]) error {
				return retrieved.LoadReportTexts(ctx, exec, mods...)
			},
		),
	}
}

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

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

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

	related.R.DestinationTextLogs = CommsTextLogSlice{o}

	o.R.DestinationPhone = related
	return nil
}

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

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

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

		for _, rel := range commsPhones {

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

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

			o.R.DestinationPhone = rel
			break
		}
	}

	return nil
}

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

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

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

	related.R.SourceTextLogs = CommsTextLogSlice{o}

	o.R.SourcePhone = related
	return nil
}

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

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

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

		for _, rel := range commsPhones {

			if !(o.Source == rel.E164) {
				continue
			}

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

			o.R.SourcePhone = rel
			break
		}
	}

	return nil
}

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

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

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

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

	o.R.ResponseTextLogCommunications = related
	return nil
}

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

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

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

		o.R.ResponseTextLogCommunications = nil
	}

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

		for _, rel := range communications {

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

			rel.R.ResponseTextLogTextLog = o

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

	return nil
}

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

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

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

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

	o.R.SourceTextLogCommunications = related
	return nil
}

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

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

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

		o.R.SourceTextLogCommunications = nil
	}

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

		for _, rel := range communications {

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

			rel.R.SourceTextLogTextLog = o

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

	return nil
}

// LoadReportLogs loads the commsTextLog's ReportLogs into the .R struct
func (o *CommsTextLog) 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.TextLog = o
	}

	o.R.ReportLogs = related
	return nil
}

// LoadReportLogs loads the commsTextLog's ReportLogs into the .R struct
func (os CommsTextLogSlice) 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.TextLogID.IsValue() {
				continue
			}
			if !(rel.TextLogID.IsValue() && o.ID == rel.TextLogID.MustGet()) {
				continue
			}

			rel.R.TextLog = o

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

	return nil
}

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

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

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

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

	o.R.ReportTexts = related
	return nil
}

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

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

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

		o.R.ReportTexts = nil
	}

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

		for _, rel := range reportTexts {

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

			rel.R.TextLog = o

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

	return nil
}
