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

// Lead is an object representing the database table.
type Lead struct {
	Created        time.Time       `db:"created" `
	Creator        int32           `db:"creator" `
	ID             int32           `db:"id,pk" `
	OrganizationID int32           `db:"organization_id" `
	SiteID         null.Val[int32] `db:"site_id" `
	Type           enums.Leadtype  `db:"type_" `

	R leadR `db:"-" `
}

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

// Leads contains methods to work with the lead table
var Leads = psql.NewTablex[*Lead, LeadSlice, *LeadSetter]("", "lead", buildLeadColumns("lead"))

// LeadsQuery is a query on the lead table
type LeadsQuery = *psql.ViewQuery[*Lead, LeadSlice]

// leadR is where relationships are stored.
type leadR struct {
	ComplianceReportRequests ComplianceReportRequestSlice // compliance_report_request.compliance_report_request_lead_id_fkey
	CreatorUser              *User                        // lead.lead_creator_fkey
	Organization             *Organization                // lead.lead_organization_id_fkey
	Site                     *Site                        // lead.lead_site_id_fkey
}

func buildLeadColumns(alias string) leadColumns {
	return leadColumns{
		ColumnsExpr: expr.NewColumnsExpr(
			"created", "creator", "id", "organization_id", "site_id", "type_",
		).WithParent("lead"),
		tableAlias:     alias,
		Created:        psql.Quote(alias, "created"),
		Creator:        psql.Quote(alias, "creator"),
		ID:             psql.Quote(alias, "id"),
		OrganizationID: psql.Quote(alias, "organization_id"),
		SiteID:         psql.Quote(alias, "site_id"),
		Type:           psql.Quote(alias, "type_"),
	}
}

type leadColumns struct {
	expr.ColumnsExpr
	tableAlias     string
	Created        psql.Expression
	Creator        psql.Expression
	ID             psql.Expression
	OrganizationID psql.Expression
	SiteID         psql.Expression
	Type           psql.Expression
}

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

func (leadColumns) AliasedAs(alias string) leadColumns {
	return buildLeadColumns(alias)
}

// LeadSetter is used for insert/upsert/update operations
// All values are optional, and do not have to be set
// Generated columns are not included
type LeadSetter struct {
	Created        omit.Val[time.Time]      `db:"created" `
	Creator        omit.Val[int32]          `db:"creator" `
	ID             omit.Val[int32]          `db:"id,pk" `
	OrganizationID omit.Val[int32]          `db:"organization_id" `
	SiteID         omitnull.Val[int32]      `db:"site_id" `
	Type           omit.Val[enums.Leadtype] `db:"type_" `
}

func (s LeadSetter) SetColumns() []string {
	vals := make([]string, 0, 6)
	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.OrganizationID.IsValue() {
		vals = append(vals, "organization_id")
	}
	if !s.SiteID.IsUnset() {
		vals = append(vals, "site_id")
	}
	if s.Type.IsValue() {
		vals = append(vals, "type_")
	}
	return vals
}

func (s LeadSetter) Overwrite(t *Lead) {
	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.OrganizationID.IsValue() {
		t.OrganizationID = s.OrganizationID.MustGet()
	}
	if !s.SiteID.IsUnset() {
		t.SiteID = s.SiteID.MustGetNull()
	}
	if s.Type.IsValue() {
		t.Type = s.Type.MustGet()
	}
}

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

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

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

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

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

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

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

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

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

	return exprs
}

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

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

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

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

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

	return err
}

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

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

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

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

	return err
}

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

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

			return err
		}))

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

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

			return err
		}))

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

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

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

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

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

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

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

	o.copyMatchingRows(o2...)

	return nil
}

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

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

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

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

// Organization starts a query for related objects on organization
func (o *Lead) Organization(mods ...bob.Mod[*dialect.SelectQuery]) OrganizationsQuery {
	return Organizations.Query(append(mods,
		sm.Where(Organizations.Columns.ID.EQ(psql.Arg(o.OrganizationID))),
	)...)
}

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

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

// Site starts a query for related objects on site
func (o *Lead) Site(mods ...bob.Mod[*dialect.SelectQuery]) SitesQuery {
	return Sites.Query(append(mods,
		sm.Where(Sites.Columns.ID.EQ(psql.Arg(o.SiteID))),
	)...)
}

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

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

func insertLeadComplianceReportRequests0(ctx context.Context, exec bob.Executor, complianceReportRequests1 []*ComplianceReportRequestSetter, lead0 *Lead) (ComplianceReportRequestSlice, error) {
	for i := range complianceReportRequests1 {
		complianceReportRequests1[i].LeadID = omitnull.From(lead0.ID)
	}

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

	return ret, nil
}

func attachLeadComplianceReportRequests0(ctx context.Context, exec bob.Executor, count int, complianceReportRequests1 ComplianceReportRequestSlice, lead0 *Lead) (ComplianceReportRequestSlice, error) {
	setter := &ComplianceReportRequestSetter{
		LeadID: omitnull.From(lead0.ID),
	}

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

	return complianceReportRequests1, nil
}

func (lead0 *Lead) InsertComplianceReportRequests(ctx context.Context, exec bob.Executor, related ...*ComplianceReportRequestSetter) error {
	if len(related) == 0 {
		return nil
	}

	var err error

	complianceReportRequests1, err := insertLeadComplianceReportRequests0(ctx, exec, related, lead0)
	if err != nil {
		return err
	}

	lead0.R.ComplianceReportRequests = append(lead0.R.ComplianceReportRequests, complianceReportRequests1...)

	for _, rel := range complianceReportRequests1 {
		rel.R.Lead = lead0
	}
	return nil
}

func (lead0 *Lead) AttachComplianceReportRequests(ctx context.Context, exec bob.Executor, related ...*ComplianceReportRequest) error {
	if len(related) == 0 {
		return nil
	}

	var err error
	complianceReportRequests1 := ComplianceReportRequestSlice(related)

	_, err = attachLeadComplianceReportRequests0(ctx, exec, len(related), complianceReportRequests1, lead0)
	if err != nil {
		return err
	}

	lead0.R.ComplianceReportRequests = append(lead0.R.ComplianceReportRequests, complianceReportRequests1...)

	for _, rel := range related {
		rel.R.Lead = lead0
	}

	return nil
}

func attachLeadCreatorUser0(ctx context.Context, exec bob.Executor, count int, lead0 *Lead, user1 *User) (*Lead, error) {
	setter := &LeadSetter{
		Creator: omit.From(user1.ID),
	}

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

	return lead0, nil
}

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

	lead0.R.CreatorUser = user1

	user1.R.CreatorLeads = append(user1.R.CreatorLeads, lead0)

	return nil
}

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

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

	lead0.R.CreatorUser = user1

	user1.R.CreatorLeads = append(user1.R.CreatorLeads, lead0)

	return nil
}

func attachLeadOrganization0(ctx context.Context, exec bob.Executor, count int, lead0 *Lead, organization1 *Organization) (*Lead, error) {
	setter := &LeadSetter{
		OrganizationID: omit.From(organization1.ID),
	}

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

	return lead0, nil
}

func (lead0 *Lead) InsertOrganization(ctx context.Context, exec bob.Executor, related *OrganizationSetter) error {
	var err error

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

	_, err = attachLeadOrganization0(ctx, exec, 1, lead0, organization1)
	if err != nil {
		return err
	}

	lead0.R.Organization = organization1

	organization1.R.Leads = append(organization1.R.Leads, lead0)

	return nil
}

func (lead0 *Lead) AttachOrganization(ctx context.Context, exec bob.Executor, organization1 *Organization) error {
	var err error

	_, err = attachLeadOrganization0(ctx, exec, 1, lead0, organization1)
	if err != nil {
		return err
	}

	lead0.R.Organization = organization1

	organization1.R.Leads = append(organization1.R.Leads, lead0)

	return nil
}

func attachLeadSite0(ctx context.Context, exec bob.Executor, count int, lead0 *Lead, site1 *Site) (*Lead, error) {
	setter := &LeadSetter{
		SiteID: omitnull.From(site1.ID),
	}

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

	return lead0, nil
}

func (lead0 *Lead) InsertSite(ctx context.Context, exec bob.Executor, related *SiteSetter) error {
	var err error

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

	_, err = attachLeadSite0(ctx, exec, 1, lead0, site1)
	if err != nil {
		return err
	}

	lead0.R.Site = site1

	site1.R.Leads = append(site1.R.Leads, lead0)

	return nil
}

func (lead0 *Lead) AttachSite(ctx context.Context, exec bob.Executor, site1 *Site) error {
	var err error

	_, err = attachLeadSite0(ctx, exec, 1, lead0, site1)
	if err != nil {
		return err
	}

	lead0.R.Site = site1

	site1.R.Leads = append(site1.R.Leads, lead0)

	return nil
}

type leadWhere[Q psql.Filterable] struct {
	Created        psql.WhereMod[Q, time.Time]
	Creator        psql.WhereMod[Q, int32]
	ID             psql.WhereMod[Q, int32]
	OrganizationID psql.WhereMod[Q, int32]
	SiteID         psql.WhereNullMod[Q, int32]
	Type           psql.WhereMod[Q, enums.Leadtype]
}

func (leadWhere[Q]) AliasedAs(alias string) leadWhere[Q] {
	return buildLeadWhere[Q](buildLeadColumns(alias))
}

func buildLeadWhere[Q psql.Filterable](cols leadColumns) leadWhere[Q] {
	return leadWhere[Q]{
		Created:        psql.Where[Q, time.Time](cols.Created),
		Creator:        psql.Where[Q, int32](cols.Creator),
		ID:             psql.Where[Q, int32](cols.ID),
		OrganizationID: psql.Where[Q, int32](cols.OrganizationID),
		SiteID:         psql.WhereNull[Q, int32](cols.SiteID),
		Type:           psql.Where[Q, enums.Leadtype](cols.Type),
	}
}

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

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

		o.R.ComplianceReportRequests = rels

		for _, rel := range rels {
			if rel != nil {
				rel.R.Lead = o
			}
		}
		return nil
	case "CreatorUser":
		rel, ok := retrieved.(*User)
		if !ok {
			return fmt.Errorf("lead cannot load %T as %q", retrieved, name)
		}

		o.R.CreatorUser = rel

		if rel != nil {
			rel.R.CreatorLeads = LeadSlice{o}
		}
		return nil
	case "Organization":
		rel, ok := retrieved.(*Organization)
		if !ok {
			return fmt.Errorf("lead cannot load %T as %q", retrieved, name)
		}

		o.R.Organization = rel

		if rel != nil {
			rel.R.Leads = LeadSlice{o}
		}
		return nil
	case "Site":
		rel, ok := retrieved.(*Site)
		if !ok {
			return fmt.Errorf("lead cannot load %T as %q", retrieved, name)
		}

		o.R.Site = rel

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

type leadPreloader struct {
	CreatorUser  func(...psql.PreloadOption) psql.Preloader
	Organization func(...psql.PreloadOption) psql.Preloader
	Site         func(...psql.PreloadOption) psql.Preloader
}

func buildLeadPreloader() leadPreloader {
	return leadPreloader{
		CreatorUser: func(opts ...psql.PreloadOption) psql.Preloader {
			return psql.Preload[*User, UserSlice](psql.PreloadRel{
				Name: "CreatorUser",
				Sides: []psql.PreloadSide{
					{
						From:        Leads,
						To:          Users,
						FromColumns: []string{"creator"},
						ToColumns:   []string{"id"},
					},
				},
			}, Users.Columns.Names(), opts...)
		},
		Organization: func(opts ...psql.PreloadOption) psql.Preloader {
			return psql.Preload[*Organization, OrganizationSlice](psql.PreloadRel{
				Name: "Organization",
				Sides: []psql.PreloadSide{
					{
						From:        Leads,
						To:          Organizations,
						FromColumns: []string{"organization_id"},
						ToColumns:   []string{"id"},
					},
				},
			}, Organizations.Columns.Names(), opts...)
		},
		Site: func(opts ...psql.PreloadOption) psql.Preloader {
			return psql.Preload[*Site, SiteSlice](psql.PreloadRel{
				Name: "Site",
				Sides: []psql.PreloadSide{
					{
						From:        Leads,
						To:          Sites,
						FromColumns: []string{"site_id"},
						ToColumns:   []string{"id"},
					},
				},
			}, Sites.Columns.Names(), opts...)
		},
	}
}

type leadThenLoader[Q orm.Loadable] struct {
	ComplianceReportRequests func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q]
	CreatorUser              func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q]
	Organization             func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q]
	Site                     func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q]
}

func buildLeadThenLoader[Q orm.Loadable]() leadThenLoader[Q] {
	type ComplianceReportRequestsLoadInterface interface {
		LoadComplianceReportRequests(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error
	}
	type CreatorUserLoadInterface interface {
		LoadCreatorUser(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error
	}
	type OrganizationLoadInterface interface {
		LoadOrganization(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error
	}
	type SiteLoadInterface interface {
		LoadSite(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error
	}

	return leadThenLoader[Q]{
		ComplianceReportRequests: thenLoadBuilder[Q](
			"ComplianceReportRequests",
			func(ctx context.Context, exec bob.Executor, retrieved ComplianceReportRequestsLoadInterface, mods ...bob.Mod[*dialect.SelectQuery]) error {
				return retrieved.LoadComplianceReportRequests(ctx, exec, mods...)
			},
		),
		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...)
			},
		),
		Organization: thenLoadBuilder[Q](
			"Organization",
			func(ctx context.Context, exec bob.Executor, retrieved OrganizationLoadInterface, mods ...bob.Mod[*dialect.SelectQuery]) error {
				return retrieved.LoadOrganization(ctx, exec, mods...)
			},
		),
		Site: thenLoadBuilder[Q](
			"Site",
			func(ctx context.Context, exec bob.Executor, retrieved SiteLoadInterface, mods ...bob.Mod[*dialect.SelectQuery]) error {
				return retrieved.LoadSite(ctx, exec, mods...)
			},
		),
	}
}

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

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

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

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

	o.R.ComplianceReportRequests = related
	return nil
}

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

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

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

		o.R.ComplianceReportRequests = nil
	}

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

		for _, rel := range complianceReportRequests {

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

			rel.R.Lead = o

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

	return nil
}

// LoadCreatorUser loads the lead's CreatorUser into the .R struct
func (o *Lead) 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.CreatorLeads = LeadSlice{o}

	o.R.CreatorUser = related
	return nil
}

// LoadCreatorUser loads the lead's CreatorUser into the .R struct
func (os LeadSlice) 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.CreatorLeads = append(rel.R.CreatorLeads, o)

			o.R.CreatorUser = rel
			break
		}
	}

	return nil
}

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

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

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

	related.R.Leads = LeadSlice{o}

	o.R.Organization = related
	return nil
}

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

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

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

		for _, rel := range organizations {

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

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

			o.R.Organization = rel
			break
		}
	}

	return nil
}

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

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

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

	related.R.Leads = LeadSlice{o}

	o.R.Site = related
	return nil
}

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

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

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

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

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

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

			o.R.Site = rel
			break
		}
	}

	return nil
}
