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

// ComplianceReportRequest is an object representing the database table.
type ComplianceReportRequest struct {
	Created  time.Time       `db:"created" `
	Creator  int32           `db:"creator" `
	ID       int32           `db:"id,pk" `
	PublicID string          `db:"public_id" `
	LeadID   null.Val[int32] `db:"lead_id" `

	R complianceReportRequestR `db:"-" `
}

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

// ComplianceReportRequests contains methods to work with the compliance_report_request table
var ComplianceReportRequests = psql.NewTablex[*ComplianceReportRequest, ComplianceReportRequestSlice, *ComplianceReportRequestSetter]("", "compliance_report_request", buildComplianceReportRequestColumns("compliance_report_request"))

// ComplianceReportRequestsQuery is a query on the compliance_report_request table
type ComplianceReportRequestsQuery = *psql.ViewQuery[*ComplianceReportRequest, ComplianceReportRequestSlice]

// complianceReportRequestR is where relationships are stored.
type complianceReportRequestR struct {
	CreatorUser                    *User                              // compliance_report_request.compliance_report_request_creator_fkey
	Lead                           *Lead                              // compliance_report_request.compliance_report_request_lead_id_fkey
	ComplianceReportRequestMailers ComplianceReportRequestMailerSlice // compliance_report_request_mailer.compliance_report_request_mai_compliance_report_request_id_fkey
}

func buildComplianceReportRequestColumns(alias string) complianceReportRequestColumns {
	return complianceReportRequestColumns{
		ColumnsExpr: expr.NewColumnsExpr(
			"created", "creator", "id", "public_id", "lead_id",
		).WithParent("compliance_report_request"),
		tableAlias: alias,
		Created:    psql.Quote(alias, "created"),
		Creator:    psql.Quote(alias, "creator"),
		ID:         psql.Quote(alias, "id"),
		PublicID:   psql.Quote(alias, "public_id"),
		LeadID:     psql.Quote(alias, "lead_id"),
	}
}

type complianceReportRequestColumns struct {
	expr.ColumnsExpr
	tableAlias string
	Created    psql.Expression
	Creator    psql.Expression
	ID         psql.Expression
	PublicID   psql.Expression
	LeadID     psql.Expression
}

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

func (complianceReportRequestColumns) AliasedAs(alias string) complianceReportRequestColumns {
	return buildComplianceReportRequestColumns(alias)
}

// ComplianceReportRequestSetter is used for insert/upsert/update operations
// All values are optional, and do not have to be set
// Generated columns are not included
type ComplianceReportRequestSetter struct {
	Created  omit.Val[time.Time] `db:"created" `
	Creator  omit.Val[int32]     `db:"creator" `
	ID       omit.Val[int32]     `db:"id,pk" `
	PublicID omit.Val[string]    `db:"public_id" `
	LeadID   omitnull.Val[int32] `db:"lead_id" `
}

func (s ComplianceReportRequestSetter) SetColumns() []string {
	vals := make([]string, 0, 5)
	if s.Created.IsValue() {
		vals = append(vals, "created")
	}
	if s.Creator.IsValue() {
		vals = append(vals, "creator")
	}
	if s.ID.IsValue() {
		vals = append(vals, "id")
	}
	if s.PublicID.IsValue() {
		vals = append(vals, "public_id")
	}
	if !s.LeadID.IsUnset() {
		vals = append(vals, "lead_id")
	}
	return vals
}

func (s ComplianceReportRequestSetter) Overwrite(t *ComplianceReportRequest) {
	if s.Created.IsValue() {
		t.Created = s.Created.MustGet()
	}
	if s.Creator.IsValue() {
		t.Creator = s.Creator.MustGet()
	}
	if s.ID.IsValue() {
		t.ID = s.ID.MustGet()
	}
	if s.PublicID.IsValue() {
		t.PublicID = s.PublicID.MustGet()
	}
	if !s.LeadID.IsUnset() {
		t.LeadID = s.LeadID.MustGetNull()
	}
}

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

		if s.Creator.IsValue() {
			vals[1] = psql.Arg(s.Creator.MustGet())
		} 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.PublicID.IsValue() {
			vals[3] = psql.Arg(s.PublicID.MustGet())
		} else {
			vals[3] = psql.Raw("DEFAULT")
		}

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

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

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

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

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

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

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

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

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

	return exprs
}

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

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

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

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

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

	return err
}

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

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

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

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

	return err
}

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

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

			return err
		}))

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

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

			return err
		}))

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

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

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

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

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

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

	o2, err := ComplianceReportRequests.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 *ComplianceReportRequest) CreatorUser(mods ...bob.Mod[*dialect.SelectQuery]) UsersQuery {
	return Users.Query(append(mods,
		sm.Where(Users.Columns.ID.EQ(psql.Arg(o.Creator))),
	)...)
}

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

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

// Lead starts a query for related objects on lead
func (o *ComplianceReportRequest) Lead(mods ...bob.Mod[*dialect.SelectQuery]) LeadsQuery {
	return Leads.Query(append(mods,
		sm.Where(Leads.Columns.ID.EQ(psql.Arg(o.LeadID))),
	)...)
}

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

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

// ComplianceReportRequestMailers starts a query for related objects on compliance_report_request_mailer
func (o *ComplianceReportRequest) ComplianceReportRequestMailers(mods ...bob.Mod[*dialect.SelectQuery]) ComplianceReportRequestMailersQuery {
	return ComplianceReportRequestMailers.Query(append(mods,
		sm.Where(ComplianceReportRequestMailers.Columns.ComplianceReportRequestID.EQ(psql.Arg(o.ID))),
	)...)
}

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

func attachComplianceReportRequestCreatorUser0(ctx context.Context, exec bob.Executor, count int, complianceReportRequest0 *ComplianceReportRequest, user1 *User) (*ComplianceReportRequest, error) {
	setter := &ComplianceReportRequestSetter{
		Creator: omit.From(user1.ID),
	}

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

	return complianceReportRequest0, nil
}

func (complianceReportRequest0 *ComplianceReportRequest) 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 = attachComplianceReportRequestCreatorUser0(ctx, exec, 1, complianceReportRequest0, user1)
	if err != nil {
		return err
	}

	complianceReportRequest0.R.CreatorUser = user1

	user1.R.CreatorComplianceReportRequests = append(user1.R.CreatorComplianceReportRequests, complianceReportRequest0)

	return nil
}

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

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

	complianceReportRequest0.R.CreatorUser = user1

	user1.R.CreatorComplianceReportRequests = append(user1.R.CreatorComplianceReportRequests, complianceReportRequest0)

	return nil
}

func attachComplianceReportRequestLead0(ctx context.Context, exec bob.Executor, count int, complianceReportRequest0 *ComplianceReportRequest, lead1 *Lead) (*ComplianceReportRequest, error) {
	setter := &ComplianceReportRequestSetter{
		LeadID: omitnull.From(lead1.ID),
	}

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

	return complianceReportRequest0, nil
}

func (complianceReportRequest0 *ComplianceReportRequest) InsertLead(ctx context.Context, exec bob.Executor, related *LeadSetter) error {
	var err error

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

	_, err = attachComplianceReportRequestLead0(ctx, exec, 1, complianceReportRequest0, lead1)
	if err != nil {
		return err
	}

	complianceReportRequest0.R.Lead = lead1

	lead1.R.ComplianceReportRequests = append(lead1.R.ComplianceReportRequests, complianceReportRequest0)

	return nil
}

func (complianceReportRequest0 *ComplianceReportRequest) AttachLead(ctx context.Context, exec bob.Executor, lead1 *Lead) error {
	var err error

	_, err = attachComplianceReportRequestLead0(ctx, exec, 1, complianceReportRequest0, lead1)
	if err != nil {
		return err
	}

	complianceReportRequest0.R.Lead = lead1

	lead1.R.ComplianceReportRequests = append(lead1.R.ComplianceReportRequests, complianceReportRequest0)

	return nil
}

func insertComplianceReportRequestComplianceReportRequestMailers0(ctx context.Context, exec bob.Executor, complianceReportRequestMailers1 []*ComplianceReportRequestMailerSetter, complianceReportRequest0 *ComplianceReportRequest) (ComplianceReportRequestMailerSlice, error) {
	for i := range complianceReportRequestMailers1 {
		complianceReportRequestMailers1[i].ComplianceReportRequestID = omit.From(complianceReportRequest0.ID)
	}

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

	return ret, nil
}

func attachComplianceReportRequestComplianceReportRequestMailers0(ctx context.Context, exec bob.Executor, count int, complianceReportRequestMailers1 ComplianceReportRequestMailerSlice, complianceReportRequest0 *ComplianceReportRequest) (ComplianceReportRequestMailerSlice, error) {
	setter := &ComplianceReportRequestMailerSetter{
		ComplianceReportRequestID: omit.From(complianceReportRequest0.ID),
	}

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

	return complianceReportRequestMailers1, nil
}

func (complianceReportRequest0 *ComplianceReportRequest) InsertComplianceReportRequestMailers(ctx context.Context, exec bob.Executor, related ...*ComplianceReportRequestMailerSetter) error {
	if len(related) == 0 {
		return nil
	}

	var err error

	complianceReportRequestMailers1, err := insertComplianceReportRequestComplianceReportRequestMailers0(ctx, exec, related, complianceReportRequest0)
	if err != nil {
		return err
	}

	complianceReportRequest0.R.ComplianceReportRequestMailers = append(complianceReportRequest0.R.ComplianceReportRequestMailers, complianceReportRequestMailers1...)

	for _, rel := range complianceReportRequestMailers1 {
		rel.R.ComplianceReportRequest = complianceReportRequest0
	}
	return nil
}

func (complianceReportRequest0 *ComplianceReportRequest) AttachComplianceReportRequestMailers(ctx context.Context, exec bob.Executor, related ...*ComplianceReportRequestMailer) error {
	if len(related) == 0 {
		return nil
	}

	var err error
	complianceReportRequestMailers1 := ComplianceReportRequestMailerSlice(related)

	_, err = attachComplianceReportRequestComplianceReportRequestMailers0(ctx, exec, len(related), complianceReportRequestMailers1, complianceReportRequest0)
	if err != nil {
		return err
	}

	complianceReportRequest0.R.ComplianceReportRequestMailers = append(complianceReportRequest0.R.ComplianceReportRequestMailers, complianceReportRequestMailers1...)

	for _, rel := range related {
		rel.R.ComplianceReportRequest = complianceReportRequest0
	}

	return nil
}

type complianceReportRequestWhere[Q psql.Filterable] struct {
	Created  psql.WhereMod[Q, time.Time]
	Creator  psql.WhereMod[Q, int32]
	ID       psql.WhereMod[Q, int32]
	PublicID psql.WhereMod[Q, string]
	LeadID   psql.WhereNullMod[Q, int32]
}

func (complianceReportRequestWhere[Q]) AliasedAs(alias string) complianceReportRequestWhere[Q] {
	return buildComplianceReportRequestWhere[Q](buildComplianceReportRequestColumns(alias))
}

func buildComplianceReportRequestWhere[Q psql.Filterable](cols complianceReportRequestColumns) complianceReportRequestWhere[Q] {
	return complianceReportRequestWhere[Q]{
		Created:  psql.Where[Q, time.Time](cols.Created),
		Creator:  psql.Where[Q, int32](cols.Creator),
		ID:       psql.Where[Q, int32](cols.ID),
		PublicID: psql.Where[Q, string](cols.PublicID),
		LeadID:   psql.WhereNull[Q, int32](cols.LeadID),
	}
}

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

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

		o.R.CreatorUser = rel

		if rel != nil {
			rel.R.CreatorComplianceReportRequests = ComplianceReportRequestSlice{o}
		}
		return nil
	case "Lead":
		rel, ok := retrieved.(*Lead)
		if !ok {
			return fmt.Errorf("complianceReportRequest cannot load %T as %q", retrieved, name)
		}

		o.R.Lead = rel

		if rel != nil {
			rel.R.ComplianceReportRequests = ComplianceReportRequestSlice{o}
		}
		return nil
	case "ComplianceReportRequestMailers":
		rels, ok := retrieved.(ComplianceReportRequestMailerSlice)
		if !ok {
			return fmt.Errorf("complianceReportRequest cannot load %T as %q", retrieved, name)
		}

		o.R.ComplianceReportRequestMailers = rels

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

type complianceReportRequestPreloader struct {
	CreatorUser func(...psql.PreloadOption) psql.Preloader
	Lead        func(...psql.PreloadOption) psql.Preloader
}

func buildComplianceReportRequestPreloader() complianceReportRequestPreloader {
	return complianceReportRequestPreloader{
		CreatorUser: func(opts ...psql.PreloadOption) psql.Preloader {
			return psql.Preload[*User, UserSlice](psql.PreloadRel{
				Name: "CreatorUser",
				Sides: []psql.PreloadSide{
					{
						From:        ComplianceReportRequests,
						To:          Users,
						FromColumns: []string{"creator"},
						ToColumns:   []string{"id"},
					},
				},
			}, Users.Columns.Names(), opts...)
		},
		Lead: func(opts ...psql.PreloadOption) psql.Preloader {
			return psql.Preload[*Lead, LeadSlice](psql.PreloadRel{
				Name: "Lead",
				Sides: []psql.PreloadSide{
					{
						From:        ComplianceReportRequests,
						To:          Leads,
						FromColumns: []string{"lead_id"},
						ToColumns:   []string{"id"},
					},
				},
			}, Leads.Columns.Names(), opts...)
		},
	}
}

type complianceReportRequestThenLoader[Q orm.Loadable] struct {
	CreatorUser                    func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q]
	Lead                           func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q]
	ComplianceReportRequestMailers func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q]
}

func buildComplianceReportRequestThenLoader[Q orm.Loadable]() complianceReportRequestThenLoader[Q] {
	type CreatorUserLoadInterface interface {
		LoadCreatorUser(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error
	}
	type LeadLoadInterface interface {
		LoadLead(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error
	}
	type ComplianceReportRequestMailersLoadInterface interface {
		LoadComplianceReportRequestMailers(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error
	}

	return complianceReportRequestThenLoader[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...)
			},
		),
		Lead: thenLoadBuilder[Q](
			"Lead",
			func(ctx context.Context, exec bob.Executor, retrieved LeadLoadInterface, mods ...bob.Mod[*dialect.SelectQuery]) error {
				return retrieved.LoadLead(ctx, exec, mods...)
			},
		),
		ComplianceReportRequestMailers: thenLoadBuilder[Q](
			"ComplianceReportRequestMailers",
			func(ctx context.Context, exec bob.Executor, retrieved ComplianceReportRequestMailersLoadInterface, mods ...bob.Mod[*dialect.SelectQuery]) error {
				return retrieved.LoadComplianceReportRequestMailers(ctx, exec, mods...)
			},
		),
	}
}

// LoadCreatorUser loads the complianceReportRequest's CreatorUser into the .R struct
func (o *ComplianceReportRequest) 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.CreatorComplianceReportRequests = ComplianceReportRequestSlice{o}

	o.R.CreatorUser = related
	return nil
}

// LoadCreatorUser loads the complianceReportRequest's CreatorUser into the .R struct
func (os ComplianceReportRequestSlice) 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.Creator == rel.ID) {
				continue
			}

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

			o.R.CreatorUser = rel
			break
		}
	}

	return nil
}

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

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

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

	related.R.ComplianceReportRequests = ComplianceReportRequestSlice{o}

	o.R.Lead = related
	return nil
}

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

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

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

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

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

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

			o.R.Lead = rel
			break
		}
	}

	return nil
}

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

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

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

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

	o.R.ComplianceReportRequestMailers = related
	return nil
}

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

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

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

		o.R.ComplianceReportRequestMailers = nil
	}

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

		for _, rel := range complianceReportRequestMailers {

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

			rel.R.ComplianceReportRequest = o

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

	return nil
}
