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

// PublicreportReportLog is an object representing the database table.
type PublicreportReportLog struct {
	Created    time.Time                       `db:"created" `
	EmailLogID null.Val[int32]                 `db:"email_log_id" `
	ID         int32                           `db:"id,pk" `
	ReportID   int32                           `db:"report_id" `
	TextLogID  null.Val[int32]                 `db:"text_log_id" `
	Type       enums.PublicreportReportlogtype `db:"type_" `
	UserID     null.Val[int32]                 `db:"user_id" `

	R publicreportReportLogR `db:"-" `
}

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

// PublicreportReportLogs contains methods to work with the report_log table
var PublicreportReportLogs = psql.NewTablex[*PublicreportReportLog, PublicreportReportLogSlice, *PublicreportReportLogSetter]("publicreport", "report_log", buildPublicreportReportLogColumns("publicreport.report_log"))

// PublicreportReportLogsQuery is a query on the report_log table
type PublicreportReportLogsQuery = *psql.ViewQuery[*PublicreportReportLog, PublicreportReportLogSlice]

// publicreportReportLogR is where relationships are stored.
type publicreportReportLogR struct {
	EmailLog *CommsEmailLog      // publicreport.report_log.report_log_email_log_id_fkey
	Report   *PublicreportReport // publicreport.report_log.report_log_report_id_fkey
	TextLog  *CommsTextLog       // publicreport.report_log.report_log_text_log_id_fkey
	UserUser *User               // publicreport.report_log.report_log_user_id_fkey
}

func buildPublicreportReportLogColumns(alias string) publicreportReportLogColumns {
	return publicreportReportLogColumns{
		ColumnsExpr: expr.NewColumnsExpr(
			"created", "email_log_id", "id", "report_id", "text_log_id", "type_", "user_id",
		).WithParent("publicreport.report_log"),
		tableAlias: alias,
		Created:    psql.Quote(alias, "created"),
		EmailLogID: psql.Quote(alias, "email_log_id"),
		ID:         psql.Quote(alias, "id"),
		ReportID:   psql.Quote(alias, "report_id"),
		TextLogID:  psql.Quote(alias, "text_log_id"),
		Type:       psql.Quote(alias, "type_"),
		UserID:     psql.Quote(alias, "user_id"),
	}
}

type publicreportReportLogColumns struct {
	expr.ColumnsExpr
	tableAlias string
	Created    psql.Expression
	EmailLogID psql.Expression
	ID         psql.Expression
	ReportID   psql.Expression
	TextLogID  psql.Expression
	Type       psql.Expression
	UserID     psql.Expression
}

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

func (publicreportReportLogColumns) AliasedAs(alias string) publicreportReportLogColumns {
	return buildPublicreportReportLogColumns(alias)
}

// PublicreportReportLogSetter is used for insert/upsert/update operations
// All values are optional, and do not have to be set
// Generated columns are not included
type PublicreportReportLogSetter struct {
	Created    omit.Val[time.Time]                       `db:"created" `
	EmailLogID omitnull.Val[int32]                       `db:"email_log_id" `
	ID         omit.Val[int32]                           `db:"id,pk" `
	ReportID   omit.Val[int32]                           `db:"report_id" `
	TextLogID  omitnull.Val[int32]                       `db:"text_log_id" `
	Type       omit.Val[enums.PublicreportReportlogtype] `db:"type_" `
	UserID     omitnull.Val[int32]                       `db:"user_id" `
}

func (s PublicreportReportLogSetter) SetColumns() []string {
	vals := make([]string, 0, 7)
	if s.Created.IsValue() {
		vals = append(vals, "created")
	}
	if !s.EmailLogID.IsUnset() {
		vals = append(vals, "email_log_id")
	}
	if s.ID.IsValue() {
		vals = append(vals, "id")
	}
	if s.ReportID.IsValue() {
		vals = append(vals, "report_id")
	}
	if !s.TextLogID.IsUnset() {
		vals = append(vals, "text_log_id")
	}
	if s.Type.IsValue() {
		vals = append(vals, "type_")
	}
	if !s.UserID.IsUnset() {
		vals = append(vals, "user_id")
	}
	return vals
}

func (s PublicreportReportLogSetter) Overwrite(t *PublicreportReportLog) {
	if s.Created.IsValue() {
		t.Created = s.Created.MustGet()
	}
	if !s.EmailLogID.IsUnset() {
		t.EmailLogID = s.EmailLogID.MustGetNull()
	}
	if s.ID.IsValue() {
		t.ID = s.ID.MustGet()
	}
	if s.ReportID.IsValue() {
		t.ReportID = s.ReportID.MustGet()
	}
	if !s.TextLogID.IsUnset() {
		t.TextLogID = s.TextLogID.MustGetNull()
	}
	if s.Type.IsValue() {
		t.Type = s.Type.MustGet()
	}
	if !s.UserID.IsUnset() {
		t.UserID = s.UserID.MustGetNull()
	}
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

	return exprs
}

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

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

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

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

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

	return err
}

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

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

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

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

	return err
}

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

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

			return err
		}))

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

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

			return err
		}))

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

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

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

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

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

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

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

	o.copyMatchingRows(o2...)

	return nil
}

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

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

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

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

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

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

// TextLog starts a query for related objects on comms.text_log
func (o *PublicreportReportLog) TextLog(mods ...bob.Mod[*dialect.SelectQuery]) CommsTextLogsQuery {
	return CommsTextLogs.Query(append(mods,
		sm.Where(CommsTextLogs.Columns.ID.EQ(psql.Arg(o.TextLogID))),
	)...)
}

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

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

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

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

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

func attachPublicreportReportLogEmailLog0(ctx context.Context, exec bob.Executor, count int, publicreportReportLog0 *PublicreportReportLog, commsEmailLog1 *CommsEmailLog) (*PublicreportReportLog, error) {
	setter := &PublicreportReportLogSetter{
		EmailLogID: omitnull.From(commsEmailLog1.ID),
	}

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

	return publicreportReportLog0, nil
}

func (publicreportReportLog0 *PublicreportReportLog) InsertEmailLog(ctx context.Context, exec bob.Executor, related *CommsEmailLogSetter) error {
	var err error

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

	_, err = attachPublicreportReportLogEmailLog0(ctx, exec, 1, publicreportReportLog0, commsEmailLog1)
	if err != nil {
		return err
	}

	publicreportReportLog0.R.EmailLog = commsEmailLog1

	commsEmailLog1.R.ReportLogs = append(commsEmailLog1.R.ReportLogs, publicreportReportLog0)

	return nil
}

func (publicreportReportLog0 *PublicreportReportLog) AttachEmailLog(ctx context.Context, exec bob.Executor, commsEmailLog1 *CommsEmailLog) error {
	var err error

	_, err = attachPublicreportReportLogEmailLog0(ctx, exec, 1, publicreportReportLog0, commsEmailLog1)
	if err != nil {
		return err
	}

	publicreportReportLog0.R.EmailLog = commsEmailLog1

	commsEmailLog1.R.ReportLogs = append(commsEmailLog1.R.ReportLogs, publicreportReportLog0)

	return nil
}

func attachPublicreportReportLogReport0(ctx context.Context, exec bob.Executor, count int, publicreportReportLog0 *PublicreportReportLog, publicreportReport1 *PublicreportReport) (*PublicreportReportLog, error) {
	setter := &PublicreportReportLogSetter{
		ReportID: omit.From(publicreportReport1.ID),
	}

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

	return publicreportReportLog0, nil
}

func (publicreportReportLog0 *PublicreportReportLog) 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 = attachPublicreportReportLogReport0(ctx, exec, 1, publicreportReportLog0, publicreportReport1)
	if err != nil {
		return err
	}

	publicreportReportLog0.R.Report = publicreportReport1

	publicreportReport1.R.ReportLogs = append(publicreportReport1.R.ReportLogs, publicreportReportLog0)

	return nil
}

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

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

	publicreportReportLog0.R.Report = publicreportReport1

	publicreportReport1.R.ReportLogs = append(publicreportReport1.R.ReportLogs, publicreportReportLog0)

	return nil
}

func attachPublicreportReportLogTextLog0(ctx context.Context, exec bob.Executor, count int, publicreportReportLog0 *PublicreportReportLog, commsTextLog1 *CommsTextLog) (*PublicreportReportLog, error) {
	setter := &PublicreportReportLogSetter{
		TextLogID: omitnull.From(commsTextLog1.ID),
	}

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

	return publicreportReportLog0, nil
}

func (publicreportReportLog0 *PublicreportReportLog) InsertTextLog(ctx context.Context, exec bob.Executor, related *CommsTextLogSetter) error {
	var err error

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

	_, err = attachPublicreportReportLogTextLog0(ctx, exec, 1, publicreportReportLog0, commsTextLog1)
	if err != nil {
		return err
	}

	publicreportReportLog0.R.TextLog = commsTextLog1

	commsTextLog1.R.ReportLogs = append(commsTextLog1.R.ReportLogs, publicreportReportLog0)

	return nil
}

func (publicreportReportLog0 *PublicreportReportLog) AttachTextLog(ctx context.Context, exec bob.Executor, commsTextLog1 *CommsTextLog) error {
	var err error

	_, err = attachPublicreportReportLogTextLog0(ctx, exec, 1, publicreportReportLog0, commsTextLog1)
	if err != nil {
		return err
	}

	publicreportReportLog0.R.TextLog = commsTextLog1

	commsTextLog1.R.ReportLogs = append(commsTextLog1.R.ReportLogs, publicreportReportLog0)

	return nil
}

func attachPublicreportReportLogUserUser0(ctx context.Context, exec bob.Executor, count int, publicreportReportLog0 *PublicreportReportLog, user1 *User) (*PublicreportReportLog, error) {
	setter := &PublicreportReportLogSetter{
		UserID: omitnull.From(user1.ID),
	}

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

	return publicreportReportLog0, nil
}

func (publicreportReportLog0 *PublicreportReportLog) InsertUserUser(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 = attachPublicreportReportLogUserUser0(ctx, exec, 1, publicreportReportLog0, user1)
	if err != nil {
		return err
	}

	publicreportReportLog0.R.UserUser = user1

	user1.R.UserReportLogs = append(user1.R.UserReportLogs, publicreportReportLog0)

	return nil
}

func (publicreportReportLog0 *PublicreportReportLog) AttachUserUser(ctx context.Context, exec bob.Executor, user1 *User) error {
	var err error

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

	publicreportReportLog0.R.UserUser = user1

	user1.R.UserReportLogs = append(user1.R.UserReportLogs, publicreportReportLog0)

	return nil
}

type publicreportReportLogWhere[Q psql.Filterable] struct {
	Created    psql.WhereMod[Q, time.Time]
	EmailLogID psql.WhereNullMod[Q, int32]
	ID         psql.WhereMod[Q, int32]
	ReportID   psql.WhereMod[Q, int32]
	TextLogID  psql.WhereNullMod[Q, int32]
	Type       psql.WhereMod[Q, enums.PublicreportReportlogtype]
	UserID     psql.WhereNullMod[Q, int32]
}

func (publicreportReportLogWhere[Q]) AliasedAs(alias string) publicreportReportLogWhere[Q] {
	return buildPublicreportReportLogWhere[Q](buildPublicreportReportLogColumns(alias))
}

func buildPublicreportReportLogWhere[Q psql.Filterable](cols publicreportReportLogColumns) publicreportReportLogWhere[Q] {
	return publicreportReportLogWhere[Q]{
		Created:    psql.Where[Q, time.Time](cols.Created),
		EmailLogID: psql.WhereNull[Q, int32](cols.EmailLogID),
		ID:         psql.Where[Q, int32](cols.ID),
		ReportID:   psql.Where[Q, int32](cols.ReportID),
		TextLogID:  psql.WhereNull[Q, int32](cols.TextLogID),
		Type:       psql.Where[Q, enums.PublicreportReportlogtype](cols.Type),
		UserID:     psql.WhereNull[Q, int32](cols.UserID),
	}
}

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

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

		o.R.EmailLog = rel

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

		o.R.Report = rel

		if rel != nil {
			rel.R.ReportLogs = PublicreportReportLogSlice{o}
		}
		return nil
	case "TextLog":
		rel, ok := retrieved.(*CommsTextLog)
		if !ok {
			return fmt.Errorf("publicreportReportLog cannot load %T as %q", retrieved, name)
		}

		o.R.TextLog = rel

		if rel != nil {
			rel.R.ReportLogs = PublicreportReportLogSlice{o}
		}
		return nil
	case "UserUser":
		rel, ok := retrieved.(*User)
		if !ok {
			return fmt.Errorf("publicreportReportLog cannot load %T as %q", retrieved, name)
		}

		o.R.UserUser = rel

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

type publicreportReportLogPreloader struct {
	EmailLog func(...psql.PreloadOption) psql.Preloader
	Report   func(...psql.PreloadOption) psql.Preloader
	TextLog  func(...psql.PreloadOption) psql.Preloader
	UserUser func(...psql.PreloadOption) psql.Preloader
}

func buildPublicreportReportLogPreloader() publicreportReportLogPreloader {
	return publicreportReportLogPreloader{
		EmailLog: func(opts ...psql.PreloadOption) psql.Preloader {
			return psql.Preload[*CommsEmailLog, CommsEmailLogSlice](psql.PreloadRel{
				Name: "EmailLog",
				Sides: []psql.PreloadSide{
					{
						From:        PublicreportReportLogs,
						To:          CommsEmailLogs,
						FromColumns: []string{"email_log_id"},
						ToColumns:   []string{"id"},
					},
				},
			}, CommsEmailLogs.Columns.Names(), opts...)
		},
		Report: func(opts ...psql.PreloadOption) psql.Preloader {
			return psql.Preload[*PublicreportReport, PublicreportReportSlice](psql.PreloadRel{
				Name: "Report",
				Sides: []psql.PreloadSide{
					{
						From:        PublicreportReportLogs,
						To:          PublicreportReports,
						FromColumns: []string{"report_id"},
						ToColumns:   []string{"id"},
					},
				},
			}, PublicreportReports.Columns.Names(), opts...)
		},
		TextLog: func(opts ...psql.PreloadOption) psql.Preloader {
			return psql.Preload[*CommsTextLog, CommsTextLogSlice](psql.PreloadRel{
				Name: "TextLog",
				Sides: []psql.PreloadSide{
					{
						From:        PublicreportReportLogs,
						To:          CommsTextLogs,
						FromColumns: []string{"text_log_id"},
						ToColumns:   []string{"id"},
					},
				},
			}, CommsTextLogs.Columns.Names(), opts...)
		},
		UserUser: func(opts ...psql.PreloadOption) psql.Preloader {
			return psql.Preload[*User, UserSlice](psql.PreloadRel{
				Name: "UserUser",
				Sides: []psql.PreloadSide{
					{
						From:        PublicreportReportLogs,
						To:          Users,
						FromColumns: []string{"user_id"},
						ToColumns:   []string{"id"},
					},
				},
			}, Users.Columns.Names(), opts...)
		},
	}
}

type publicreportReportLogThenLoader[Q orm.Loadable] struct {
	EmailLog func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q]
	Report   func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q]
	TextLog  func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q]
	UserUser func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q]
}

func buildPublicreportReportLogThenLoader[Q orm.Loadable]() publicreportReportLogThenLoader[Q] {
	type EmailLogLoadInterface interface {
		LoadEmailLog(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error
	}
	type ReportLoadInterface interface {
		LoadReport(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error
	}
	type TextLogLoadInterface interface {
		LoadTextLog(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error
	}
	type UserUserLoadInterface interface {
		LoadUserUser(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error
	}

	return publicreportReportLogThenLoader[Q]{
		EmailLog: thenLoadBuilder[Q](
			"EmailLog",
			func(ctx context.Context, exec bob.Executor, retrieved EmailLogLoadInterface, mods ...bob.Mod[*dialect.SelectQuery]) error {
				return retrieved.LoadEmailLog(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...)
			},
		),
		TextLog: thenLoadBuilder[Q](
			"TextLog",
			func(ctx context.Context, exec bob.Executor, retrieved TextLogLoadInterface, mods ...bob.Mod[*dialect.SelectQuery]) error {
				return retrieved.LoadTextLog(ctx, exec, mods...)
			},
		),
		UserUser: thenLoadBuilder[Q](
			"UserUser",
			func(ctx context.Context, exec bob.Executor, retrieved UserUserLoadInterface, mods ...bob.Mod[*dialect.SelectQuery]) error {
				return retrieved.LoadUserUser(ctx, exec, mods...)
			},
		),
	}
}

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

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

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

	related.R.ReportLogs = PublicreportReportLogSlice{o}

	o.R.EmailLog = related
	return nil
}

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

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

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

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

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

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

			o.R.EmailLog = rel
			break
		}
	}

	return nil
}

// LoadReport loads the publicreportReportLog's Report into the .R struct
func (o *PublicreportReportLog) 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.ReportLogs = PublicreportReportLogSlice{o}

	o.R.Report = related
	return nil
}

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

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

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

		for _, rel := range publicreportReports {

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

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

			o.R.Report = rel
			break
		}
	}

	return nil
}

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

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

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

	related.R.ReportLogs = PublicreportReportLogSlice{o}

	o.R.TextLog = related
	return nil
}

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

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

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

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

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

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

			o.R.TextLog = rel
			break
		}
	}

	return nil
}

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

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

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

	related.R.UserReportLogs = PublicreportReportLogSlice{o}

	o.R.UserUser = related
	return nil
}

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

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

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

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

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

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

			o.R.UserUser = rel
			break
		}
	}

	return nil
}
