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

// CommsTextJob is an object representing the database table.
type CommsTextJob struct {
	Content     string                   `db:"content" `
	Created     time.Time                `db:"created" `
	Destination string                   `db:"destination" `
	ID          int32                    `db:"id,pk" `
	Type        enums.CommsTextjobtype   `db:"type_" `
	Source      enums.CommsTextjobsource `db:"source" `
	Completed   null.Val[time.Time]      `db:"completed" `
	CreatorID   null.Val[int32]          `db:"creator_id" `
	ReportID    null.Val[int32]          `db:"report_id" `

	R commsTextJobR `db:"-" `
}

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

// CommsTextJobs contains methods to work with the text_job table
var CommsTextJobs = psql.NewTablex[*CommsTextJob, CommsTextJobSlice, *CommsTextJobSetter]("comms", "text_job", buildCommsTextJobColumns("comms.text_job"))

// CommsTextJobsQuery is a query on the text_job table
type CommsTextJobsQuery = *psql.ViewQuery[*CommsTextJob, CommsTextJobSlice]

// commsTextJobR is where relationships are stored.
type commsTextJobR struct {
	CreatorUser      *User               // comms.text_job.text_job_creator_id_fkey
	DestinationPhone *CommsPhone         // comms.text_job.text_job_destination_fkey
	Report           *PublicreportReport // comms.text_job.text_job_report_id_fkey
}

func buildCommsTextJobColumns(alias string) commsTextJobColumns {
	return commsTextJobColumns{
		ColumnsExpr: expr.NewColumnsExpr(
			"content", "created", "destination", "id", "type_", "source", "completed", "creator_id", "report_id",
		).WithParent("comms.text_job"),
		tableAlias:  alias,
		Content:     psql.Quote(alias, "content"),
		Created:     psql.Quote(alias, "created"),
		Destination: psql.Quote(alias, "destination"),
		ID:          psql.Quote(alias, "id"),
		Type:        psql.Quote(alias, "type_"),
		Source:      psql.Quote(alias, "source"),
		Completed:   psql.Quote(alias, "completed"),
		CreatorID:   psql.Quote(alias, "creator_id"),
		ReportID:    psql.Quote(alias, "report_id"),
	}
}

type commsTextJobColumns struct {
	expr.ColumnsExpr
	tableAlias  string
	Content     psql.Expression
	Created     psql.Expression
	Destination psql.Expression
	ID          psql.Expression
	Type        psql.Expression
	Source      psql.Expression
	Completed   psql.Expression
	CreatorID   psql.Expression
	ReportID    psql.Expression
}

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

func (commsTextJobColumns) AliasedAs(alias string) commsTextJobColumns {
	return buildCommsTextJobColumns(alias)
}

// CommsTextJobSetter is used for insert/upsert/update operations
// All values are optional, and do not have to be set
// Generated columns are not included
type CommsTextJobSetter 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" `
	Type        omit.Val[enums.CommsTextjobtype]   `db:"type_" `
	Source      omit.Val[enums.CommsTextjobsource] `db:"source" `
	Completed   omitnull.Val[time.Time]            `db:"completed" `
	CreatorID   omitnull.Val[int32]                `db:"creator_id" `
	ReportID    omitnull.Val[int32]                `db:"report_id" `
}

func (s CommsTextJobSetter) SetColumns() []string {
	vals := make([]string, 0, 9)
	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.Type.IsValue() {
		vals = append(vals, "type_")
	}
	if s.Source.IsValue() {
		vals = append(vals, "source")
	}
	if !s.Completed.IsUnset() {
		vals = append(vals, "completed")
	}
	if !s.CreatorID.IsUnset() {
		vals = append(vals, "creator_id")
	}
	if !s.ReportID.IsUnset() {
		vals = append(vals, "report_id")
	}
	return vals
}

func (s CommsTextJobSetter) Overwrite(t *CommsTextJob) {
	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.Type.IsValue() {
		t.Type = s.Type.MustGet()
	}
	if s.Source.IsValue() {
		t.Source = s.Source.MustGet()
	}
	if !s.Completed.IsUnset() {
		t.Completed = s.Completed.MustGetNull()
	}
	if !s.CreatorID.IsUnset() {
		t.CreatorID = s.CreatorID.MustGetNull()
	}
	if !s.ReportID.IsUnset() {
		t.ReportID = s.ReportID.MustGetNull()
	}
}

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

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

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

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

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

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

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

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

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

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

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

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

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

	return exprs
}

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

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

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

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

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

	return err
}

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

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

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

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

	return err
}

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

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

			return err
		}))

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

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

			return err
		}))

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

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

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

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

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

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

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

	o.copyMatchingRows(o2...)

	return nil
}

// CreatorUser starts a query for related objects on user_
func (o *CommsTextJob) CreatorUser(mods ...bob.Mod[*dialect.SelectQuery]) UsersQuery {
	return Users.Query(append(mods,
		sm.Where(Users.Columns.ID.EQ(psql.Arg(o.CreatorID))),
	)...)
}

func (os CommsTextJobSlice) CreatorUser(mods ...bob.Mod[*dialect.SelectQuery]) UsersQuery {
	pkCreatorID := make(pgtypes.Array[null.Val[int32]], 0, len(os))
	for _, o := range os {
		if o == nil {
			continue
		}
		pkCreatorID = append(pkCreatorID, o.CreatorID)
	}
	PKArgExpr := psql.Select(sm.Columns(
		psql.F("unnest", psql.Cast(psql.Arg(pkCreatorID), "integer[]")),
	))

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

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

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

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

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

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

func attachCommsTextJobCreatorUser0(ctx context.Context, exec bob.Executor, count int, commsTextJob0 *CommsTextJob, user1 *User) (*CommsTextJob, error) {
	setter := &CommsTextJobSetter{
		CreatorID: omitnull.From(user1.ID),
	}

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

	return commsTextJob0, nil
}

func (commsTextJob0 *CommsTextJob) InsertCreatorUser(ctx context.Context, exec bob.Executor, related *UserSetter) error {
	var err error

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

	_, err = attachCommsTextJobCreatorUser0(ctx, exec, 1, commsTextJob0, user1)
	if err != nil {
		return err
	}

	commsTextJob0.R.CreatorUser = user1

	user1.R.CreatorTextJobs = append(user1.R.CreatorTextJobs, commsTextJob0)

	return nil
}

func (commsTextJob0 *CommsTextJob) AttachCreatorUser(ctx context.Context, exec bob.Executor, user1 *User) error {
	var err error

	_, err = attachCommsTextJobCreatorUser0(ctx, exec, 1, commsTextJob0, user1)
	if err != nil {
		return err
	}

	commsTextJob0.R.CreatorUser = user1

	user1.R.CreatorTextJobs = append(user1.R.CreatorTextJobs, commsTextJob0)

	return nil
}

func attachCommsTextJobDestinationPhone0(ctx context.Context, exec bob.Executor, count int, commsTextJob0 *CommsTextJob, commsPhone1 *CommsPhone) (*CommsTextJob, error) {
	setter := &CommsTextJobSetter{
		Destination: omit.From(commsPhone1.E164),
	}

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

	return commsTextJob0, nil
}

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

	commsTextJob0.R.DestinationPhone = commsPhone1

	commsPhone1.R.DestinationTextJobs = append(commsPhone1.R.DestinationTextJobs, commsTextJob0)

	return nil
}

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

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

	commsTextJob0.R.DestinationPhone = commsPhone1

	commsPhone1.R.DestinationTextJobs = append(commsPhone1.R.DestinationTextJobs, commsTextJob0)

	return nil
}

func attachCommsTextJobReport0(ctx context.Context, exec bob.Executor, count int, commsTextJob0 *CommsTextJob, publicreportReport1 *PublicreportReport) (*CommsTextJob, error) {
	setter := &CommsTextJobSetter{
		ReportID: omitnull.From(publicreportReport1.ID),
	}

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

	return commsTextJob0, nil
}

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

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

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

	commsTextJob0.R.Report = publicreportReport1

	publicreportReport1.R.TextJobs = append(publicreportReport1.R.TextJobs, commsTextJob0)

	return nil
}

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

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

	commsTextJob0.R.Report = publicreportReport1

	publicreportReport1.R.TextJobs = append(publicreportReport1.R.TextJobs, commsTextJob0)

	return nil
}

type commsTextJobWhere[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]
	Type        psql.WhereMod[Q, enums.CommsTextjobtype]
	Source      psql.WhereMod[Q, enums.CommsTextjobsource]
	Completed   psql.WhereNullMod[Q, time.Time]
	CreatorID   psql.WhereNullMod[Q, int32]
	ReportID    psql.WhereNullMod[Q, int32]
}

func (commsTextJobWhere[Q]) AliasedAs(alias string) commsTextJobWhere[Q] {
	return buildCommsTextJobWhere[Q](buildCommsTextJobColumns(alias))
}

func buildCommsTextJobWhere[Q psql.Filterable](cols commsTextJobColumns) commsTextJobWhere[Q] {
	return commsTextJobWhere[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),
		Type:        psql.Where[Q, enums.CommsTextjobtype](cols.Type),
		Source:      psql.Where[Q, enums.CommsTextjobsource](cols.Source),
		Completed:   psql.WhereNull[Q, time.Time](cols.Completed),
		CreatorID:   psql.WhereNull[Q, int32](cols.CreatorID),
		ReportID:    psql.WhereNull[Q, int32](cols.ReportID),
	}
}

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

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

		o.R.CreatorUser = rel

		if rel != nil {
			rel.R.CreatorTextJobs = CommsTextJobSlice{o}
		}
		return nil
	case "DestinationPhone":
		rel, ok := retrieved.(*CommsPhone)
		if !ok {
			return fmt.Errorf("commsTextJob cannot load %T as %q", retrieved, name)
		}

		o.R.DestinationPhone = rel

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

		o.R.Report = rel

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

type commsTextJobPreloader struct {
	CreatorUser      func(...psql.PreloadOption) psql.Preloader
	DestinationPhone func(...psql.PreloadOption) psql.Preloader
	Report           func(...psql.PreloadOption) psql.Preloader
}

func buildCommsTextJobPreloader() commsTextJobPreloader {
	return commsTextJobPreloader{
		CreatorUser: func(opts ...psql.PreloadOption) psql.Preloader {
			return psql.Preload[*User, UserSlice](psql.PreloadRel{
				Name: "CreatorUser",
				Sides: []psql.PreloadSide{
					{
						From:        CommsTextJobs,
						To:          Users,
						FromColumns: []string{"creator_id"},
						ToColumns:   []string{"id"},
					},
				},
			}, Users.Columns.Names(), opts...)
		},
		DestinationPhone: func(opts ...psql.PreloadOption) psql.Preloader {
			return psql.Preload[*CommsPhone, CommsPhoneSlice](psql.PreloadRel{
				Name: "DestinationPhone",
				Sides: []psql.PreloadSide{
					{
						From:        CommsTextJobs,
						To:          CommsPhones,
						FromColumns: []string{"destination"},
						ToColumns:   []string{"e164"},
					},
				},
			}, CommsPhones.Columns.Names(), opts...)
		},
		Report: func(opts ...psql.PreloadOption) psql.Preloader {
			return psql.Preload[*PublicreportReport, PublicreportReportSlice](psql.PreloadRel{
				Name: "Report",
				Sides: []psql.PreloadSide{
					{
						From:        CommsTextJobs,
						To:          PublicreportReports,
						FromColumns: []string{"report_id"},
						ToColumns:   []string{"id"},
					},
				},
			}, PublicreportReports.Columns.Names(), opts...)
		},
	}
}

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

func buildCommsTextJobThenLoader[Q orm.Loadable]() commsTextJobThenLoader[Q] {
	type CreatorUserLoadInterface interface {
		LoadCreatorUser(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error
	}
	type DestinationPhoneLoadInterface interface {
		LoadDestinationPhone(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error
	}
	type ReportLoadInterface interface {
		LoadReport(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error
	}

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

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

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

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

	related.R.CreatorTextJobs = CommsTextJobSlice{o}

	o.R.CreatorUser = related
	return nil
}

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

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

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

		for _, rel := range users {
			if !o.CreatorID.IsValue() {
				continue
			}

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

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

			o.R.CreatorUser = rel
			break
		}
	}

	return nil
}

// LoadDestinationPhone loads the commsTextJob's DestinationPhone into the .R struct
func (o *CommsTextJob) 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.DestinationTextJobs = CommsTextJobSlice{o}

	o.R.DestinationPhone = related
	return nil
}

// LoadDestinationPhone loads the commsTextJob's DestinationPhone into the .R struct
func (os CommsTextJobSlice) 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.DestinationTextJobs = append(rel.R.DestinationTextJobs, o)

			o.R.DestinationPhone = rel
			break
		}
	}

	return nil
}

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

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

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

	related.R.TextJobs = CommsTextJobSlice{o}

	o.R.Report = related
	return nil
}

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

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

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

		for _, rel := range publicreportReports {
			if !o.ReportID.IsValue() {
				continue
			}

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

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

			o.R.Report = rel
			break
		}
	}

	return nil
}
