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

// CommsEmailTemplate is an object representing the database table.
type CommsEmailTemplate struct {
	ContentHTML     string                      `db:"content_html" `
	ContentTXT      string                      `db:"content_txt" `
	ContentHashHTML string                      `db:"content_hash_html" `
	ContentHashTXT  string                      `db:"content_hash_txt" `
	Created         time.Time                   `db:"created" `
	ID              int32                       `db:"id,pk" `
	Superceded      null.Val[time.Time]         `db:"superceded" `
	MessageType     enums.CommsMessagetypeemail `db:"message_type" `

	R commsEmailTemplateR `db:"-" `
}

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

// CommsEmailTemplates contains methods to work with the email_template table
var CommsEmailTemplates = psql.NewTablex[*CommsEmailTemplate, CommsEmailTemplateSlice, *CommsEmailTemplateSetter]("comms", "email_template", buildCommsEmailTemplateColumns("comms.email_template"))

// CommsEmailTemplatesQuery is a query on the email_template table
type CommsEmailTemplatesQuery = *psql.ViewQuery[*CommsEmailTemplate, CommsEmailTemplateSlice]

// commsEmailTemplateR is where relationships are stored.
type commsEmailTemplateR struct {
	TemplateEmailLogs CommsEmailLogSlice // comms.email_log.email_log_template_id_fkey
}

func buildCommsEmailTemplateColumns(alias string) commsEmailTemplateColumns {
	return commsEmailTemplateColumns{
		ColumnsExpr: expr.NewColumnsExpr(
			"content_html", "content_txt", "content_hash_html", "content_hash_txt", "created", "id", "superceded", "message_type",
		).WithParent("comms.email_template"),
		tableAlias:      alias,
		ContentHTML:     psql.Quote(alias, "content_html"),
		ContentTXT:      psql.Quote(alias, "content_txt"),
		ContentHashHTML: psql.Quote(alias, "content_hash_html"),
		ContentHashTXT:  psql.Quote(alias, "content_hash_txt"),
		Created:         psql.Quote(alias, "created"),
		ID:              psql.Quote(alias, "id"),
		Superceded:      psql.Quote(alias, "superceded"),
		MessageType:     psql.Quote(alias, "message_type"),
	}
}

type commsEmailTemplateColumns struct {
	expr.ColumnsExpr
	tableAlias      string
	ContentHTML     psql.Expression
	ContentTXT      psql.Expression
	ContentHashHTML psql.Expression
	ContentHashTXT  psql.Expression
	Created         psql.Expression
	ID              psql.Expression
	Superceded      psql.Expression
	MessageType     psql.Expression
}

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

func (commsEmailTemplateColumns) AliasedAs(alias string) commsEmailTemplateColumns {
	return buildCommsEmailTemplateColumns(alias)
}

// CommsEmailTemplateSetter is used for insert/upsert/update operations
// All values are optional, and do not have to be set
// Generated columns are not included
type CommsEmailTemplateSetter struct {
	ContentHTML     omit.Val[string]                      `db:"content_html" `
	ContentTXT      omit.Val[string]                      `db:"content_txt" `
	ContentHashHTML omit.Val[string]                      `db:"content_hash_html" `
	ContentHashTXT  omit.Val[string]                      `db:"content_hash_txt" `
	Created         omit.Val[time.Time]                   `db:"created" `
	ID              omit.Val[int32]                       `db:"id,pk" `
	Superceded      omitnull.Val[time.Time]               `db:"superceded" `
	MessageType     omit.Val[enums.CommsMessagetypeemail] `db:"message_type" `
}

func (s CommsEmailTemplateSetter) SetColumns() []string {
	vals := make([]string, 0, 8)
	if s.ContentHTML.IsValue() {
		vals = append(vals, "content_html")
	}
	if s.ContentTXT.IsValue() {
		vals = append(vals, "content_txt")
	}
	if s.ContentHashHTML.IsValue() {
		vals = append(vals, "content_hash_html")
	}
	if s.ContentHashTXT.IsValue() {
		vals = append(vals, "content_hash_txt")
	}
	if s.Created.IsValue() {
		vals = append(vals, "created")
	}
	if s.ID.IsValue() {
		vals = append(vals, "id")
	}
	if !s.Superceded.IsUnset() {
		vals = append(vals, "superceded")
	}
	if s.MessageType.IsValue() {
		vals = append(vals, "message_type")
	}
	return vals
}

func (s CommsEmailTemplateSetter) Overwrite(t *CommsEmailTemplate) {
	if s.ContentHTML.IsValue() {
		t.ContentHTML = s.ContentHTML.MustGet()
	}
	if s.ContentTXT.IsValue() {
		t.ContentTXT = s.ContentTXT.MustGet()
	}
	if s.ContentHashHTML.IsValue() {
		t.ContentHashHTML = s.ContentHashHTML.MustGet()
	}
	if s.ContentHashTXT.IsValue() {
		t.ContentHashTXT = s.ContentHashTXT.MustGet()
	}
	if s.Created.IsValue() {
		t.Created = s.Created.MustGet()
	}
	if s.ID.IsValue() {
		t.ID = s.ID.MustGet()
	}
	if !s.Superceded.IsUnset() {
		t.Superceded = s.Superceded.MustGetNull()
	}
	if s.MessageType.IsValue() {
		t.MessageType = s.MessageType.MustGet()
	}
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

	return exprs
}

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

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

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

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

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

	return err
}

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

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

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

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

	return err
}

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

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

			return err
		}))

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

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

			return err
		}))

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

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

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

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

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

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

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

	o.copyMatchingRows(o2...)

	return nil
}

// TemplateEmailLogs starts a query for related objects on comms.email_log
func (o *CommsEmailTemplate) TemplateEmailLogs(mods ...bob.Mod[*dialect.SelectQuery]) CommsEmailLogsQuery {
	return CommsEmailLogs.Query(append(mods,
		sm.Where(CommsEmailLogs.Columns.TemplateID.EQ(psql.Arg(o.ID))),
	)...)
}

func (os CommsEmailTemplateSlice) TemplateEmailLogs(mods ...bob.Mod[*dialect.SelectQuery]) CommsEmailLogsQuery {
	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 CommsEmailLogs.Query(append(mods,
		sm.Where(psql.Group(CommsEmailLogs.Columns.TemplateID).OP("IN", PKArgExpr)),
	)...)
}

func insertCommsEmailTemplateTemplateEmailLogs0(ctx context.Context, exec bob.Executor, commsEmailLogs1 []*CommsEmailLogSetter, commsEmailTemplate0 *CommsEmailTemplate) (CommsEmailLogSlice, error) {
	for i := range commsEmailLogs1 {
		commsEmailLogs1[i].TemplateID = omit.From(commsEmailTemplate0.ID)
	}

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

	return ret, nil
}

func attachCommsEmailTemplateTemplateEmailLogs0(ctx context.Context, exec bob.Executor, count int, commsEmailLogs1 CommsEmailLogSlice, commsEmailTemplate0 *CommsEmailTemplate) (CommsEmailLogSlice, error) {
	setter := &CommsEmailLogSetter{
		TemplateID: omit.From(commsEmailTemplate0.ID),
	}

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

	return commsEmailLogs1, nil
}

func (commsEmailTemplate0 *CommsEmailTemplate) InsertTemplateEmailLogs(ctx context.Context, exec bob.Executor, related ...*CommsEmailLogSetter) error {
	if len(related) == 0 {
		return nil
	}

	var err error

	commsEmailLogs1, err := insertCommsEmailTemplateTemplateEmailLogs0(ctx, exec, related, commsEmailTemplate0)
	if err != nil {
		return err
	}

	commsEmailTemplate0.R.TemplateEmailLogs = append(commsEmailTemplate0.R.TemplateEmailLogs, commsEmailLogs1...)

	for _, rel := range commsEmailLogs1 {
		rel.R.TemplateEmailTemplate = commsEmailTemplate0
	}
	return nil
}

func (commsEmailTemplate0 *CommsEmailTemplate) AttachTemplateEmailLogs(ctx context.Context, exec bob.Executor, related ...*CommsEmailLog) error {
	if len(related) == 0 {
		return nil
	}

	var err error
	commsEmailLogs1 := CommsEmailLogSlice(related)

	_, err = attachCommsEmailTemplateTemplateEmailLogs0(ctx, exec, len(related), commsEmailLogs1, commsEmailTemplate0)
	if err != nil {
		return err
	}

	commsEmailTemplate0.R.TemplateEmailLogs = append(commsEmailTemplate0.R.TemplateEmailLogs, commsEmailLogs1...)

	for _, rel := range related {
		rel.R.TemplateEmailTemplate = commsEmailTemplate0
	}

	return nil
}

type commsEmailTemplateWhere[Q psql.Filterable] struct {
	ContentHTML     psql.WhereMod[Q, string]
	ContentTXT      psql.WhereMod[Q, string]
	ContentHashHTML psql.WhereMod[Q, string]
	ContentHashTXT  psql.WhereMod[Q, string]
	Created         psql.WhereMod[Q, time.Time]
	ID              psql.WhereMod[Q, int32]
	Superceded      psql.WhereNullMod[Q, time.Time]
	MessageType     psql.WhereMod[Q, enums.CommsMessagetypeemail]
}

func (commsEmailTemplateWhere[Q]) AliasedAs(alias string) commsEmailTemplateWhere[Q] {
	return buildCommsEmailTemplateWhere[Q](buildCommsEmailTemplateColumns(alias))
}

func buildCommsEmailTemplateWhere[Q psql.Filterable](cols commsEmailTemplateColumns) commsEmailTemplateWhere[Q] {
	return commsEmailTemplateWhere[Q]{
		ContentHTML:     psql.Where[Q, string](cols.ContentHTML),
		ContentTXT:      psql.Where[Q, string](cols.ContentTXT),
		ContentHashHTML: psql.Where[Q, string](cols.ContentHashHTML),
		ContentHashTXT:  psql.Where[Q, string](cols.ContentHashTXT),
		Created:         psql.Where[Q, time.Time](cols.Created),
		ID:              psql.Where[Q, int32](cols.ID),
		Superceded:      psql.WhereNull[Q, time.Time](cols.Superceded),
		MessageType:     psql.Where[Q, enums.CommsMessagetypeemail](cols.MessageType),
	}
}

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

	switch name {
	case "TemplateEmailLogs":
		rels, ok := retrieved.(CommsEmailLogSlice)
		if !ok {
			return fmt.Errorf("commsEmailTemplate cannot load %T as %q", retrieved, name)
		}

		o.R.TemplateEmailLogs = rels

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

type commsEmailTemplatePreloader struct{}

func buildCommsEmailTemplatePreloader() commsEmailTemplatePreloader {
	return commsEmailTemplatePreloader{}
}

type commsEmailTemplateThenLoader[Q orm.Loadable] struct {
	TemplateEmailLogs func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q]
}

func buildCommsEmailTemplateThenLoader[Q orm.Loadable]() commsEmailTemplateThenLoader[Q] {
	type TemplateEmailLogsLoadInterface interface {
		LoadTemplateEmailLogs(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error
	}

	return commsEmailTemplateThenLoader[Q]{
		TemplateEmailLogs: thenLoadBuilder[Q](
			"TemplateEmailLogs",
			func(ctx context.Context, exec bob.Executor, retrieved TemplateEmailLogsLoadInterface, mods ...bob.Mod[*dialect.SelectQuery]) error {
				return retrieved.LoadTemplateEmailLogs(ctx, exec, mods...)
			},
		),
	}
}

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

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

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

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

	o.R.TemplateEmailLogs = related
	return nil
}

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

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

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

		o.R.TemplateEmailLogs = nil
	}

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

		for _, rel := range commsEmailLogs {

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

			rel.R.TemplateEmailTemplate = o

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

	return nil
}
