// 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"
	"strconv"
	"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/mods"
	"github.com/Gleipnir-Technology/bob/orm"
	"github.com/Gleipnir-Technology/bob/types/pgtypes"
	enums "github.com/Gleipnir-Technology/nidus-sync/db/enums"
	"github.com/aarondl/opt/null"
	"github.com/aarondl/opt/omit"
	"github.com/aarondl/opt/omitnull"
	"github.com/stephenafamo/scan"
)

// PublicreportQuick is an object representing the database table.
type PublicreportQuick struct {
	ID             int32                              `db:"id,pk" `
	Created        time.Time                          `db:"created" `
	Comments       string                             `db:"comments" `
	Location       null.Val[string]                   `db:"location" `
	H3cell         null.Val[string]                   `db:"h3cell" `
	PublicID       string                             `db:"public_id" `
	ReporterEmail  string                             `db:"reporter_email" `
	ReporterPhone  string                             `db:"reporter_phone" `
	Address        string                             `db:"address" `
	Status         enums.PublicreportReportstatustype `db:"status" `
	OrganizationID null.Val[int32]                    `db:"organization_id" `

	R publicreportQuickR `db:"-" `

	C publicreportQuickC `db:"-" `
}

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

// PublicreportQuicks contains methods to work with the quick table
var PublicreportQuicks = psql.NewTablex[*PublicreportQuick, PublicreportQuickSlice, *PublicreportQuickSetter]("publicreport", "quick", buildPublicreportQuickColumns("publicreport.quick"))

// PublicreportQuicksQuery is a query on the quick table
type PublicreportQuicksQuery = *psql.ViewQuery[*PublicreportQuick, PublicreportQuickSlice]

// publicreportQuickR is where relationships are stored.
type publicreportQuickR struct {
	Organization *Organization          // publicreport.quick.quick_organization_id_fkey
	Images       PublicreportImageSlice // publicreport.quick_image.quick_image_image_id_fkeypublicreport.quick_image.quick_image_quick_id_fkey
}

func buildPublicreportQuickColumns(alias string) publicreportQuickColumns {
	return publicreportQuickColumns{
		ColumnsExpr: expr.NewColumnsExpr(
			"id", "created", "comments", "location", "h3cell", "public_id", "reporter_email", "reporter_phone", "address", "status", "organization_id",
		).WithParent("publicreport.quick"),
		tableAlias:     alias,
		ID:             psql.Quote(alias, "id"),
		Created:        psql.Quote(alias, "created"),
		Comments:       psql.Quote(alias, "comments"),
		Location:       psql.Quote(alias, "location"),
		H3cell:         psql.Quote(alias, "h3cell"),
		PublicID:       psql.Quote(alias, "public_id"),
		ReporterEmail:  psql.Quote(alias, "reporter_email"),
		ReporterPhone:  psql.Quote(alias, "reporter_phone"),
		Address:        psql.Quote(alias, "address"),
		Status:         psql.Quote(alias, "status"),
		OrganizationID: psql.Quote(alias, "organization_id"),
	}
}

type publicreportQuickColumns struct {
	expr.ColumnsExpr
	tableAlias     string
	ID             psql.Expression
	Created        psql.Expression
	Comments       psql.Expression
	Location       psql.Expression
	H3cell         psql.Expression
	PublicID       psql.Expression
	ReporterEmail  psql.Expression
	ReporterPhone  psql.Expression
	Address        psql.Expression
	Status         psql.Expression
	OrganizationID psql.Expression
}

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

func (publicreportQuickColumns) AliasedAs(alias string) publicreportQuickColumns {
	return buildPublicreportQuickColumns(alias)
}

// PublicreportQuickSetter is used for insert/upsert/update operations
// All values are optional, and do not have to be set
// Generated columns are not included
type PublicreportQuickSetter struct {
	ID             omit.Val[int32]                              `db:"id,pk" `
	Created        omit.Val[time.Time]                          `db:"created" `
	Comments       omit.Val[string]                             `db:"comments" `
	Location       omitnull.Val[string]                         `db:"location" `
	H3cell         omitnull.Val[string]                         `db:"h3cell" `
	PublicID       omit.Val[string]                             `db:"public_id" `
	ReporterEmail  omit.Val[string]                             `db:"reporter_email" `
	ReporterPhone  omit.Val[string]                             `db:"reporter_phone" `
	Address        omit.Val[string]                             `db:"address" `
	Status         omit.Val[enums.PublicreportReportstatustype] `db:"status" `
	OrganizationID omitnull.Val[int32]                          `db:"organization_id" `
}

func (s PublicreportQuickSetter) SetColumns() []string {
	vals := make([]string, 0, 11)
	if s.ID.IsValue() {
		vals = append(vals, "id")
	}
	if s.Created.IsValue() {
		vals = append(vals, "created")
	}
	if s.Comments.IsValue() {
		vals = append(vals, "comments")
	}
	if !s.Location.IsUnset() {
		vals = append(vals, "location")
	}
	if !s.H3cell.IsUnset() {
		vals = append(vals, "h3cell")
	}
	if s.PublicID.IsValue() {
		vals = append(vals, "public_id")
	}
	if s.ReporterEmail.IsValue() {
		vals = append(vals, "reporter_email")
	}
	if s.ReporterPhone.IsValue() {
		vals = append(vals, "reporter_phone")
	}
	if s.Address.IsValue() {
		vals = append(vals, "address")
	}
	if s.Status.IsValue() {
		vals = append(vals, "status")
	}
	if !s.OrganizationID.IsUnset() {
		vals = append(vals, "organization_id")
	}
	return vals
}

func (s PublicreportQuickSetter) Overwrite(t *PublicreportQuick) {
	if s.ID.IsValue() {
		t.ID = s.ID.MustGet()
	}
	if s.Created.IsValue() {
		t.Created = s.Created.MustGet()
	}
	if s.Comments.IsValue() {
		t.Comments = s.Comments.MustGet()
	}
	if !s.Location.IsUnset() {
		t.Location = s.Location.MustGetNull()
	}
	if !s.H3cell.IsUnset() {
		t.H3cell = s.H3cell.MustGetNull()
	}
	if s.PublicID.IsValue() {
		t.PublicID = s.PublicID.MustGet()
	}
	if s.ReporterEmail.IsValue() {
		t.ReporterEmail = s.ReporterEmail.MustGet()
	}
	if s.ReporterPhone.IsValue() {
		t.ReporterPhone = s.ReporterPhone.MustGet()
	}
	if s.Address.IsValue() {
		t.Address = s.Address.MustGet()
	}
	if s.Status.IsValue() {
		t.Status = s.Status.MustGet()
	}
	if !s.OrganizationID.IsUnset() {
		t.OrganizationID = s.OrganizationID.MustGetNull()
	}
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

	return exprs
}

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

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

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

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

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

	return err
}

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

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

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

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

	return err
}

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

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

			return err
		}))

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

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

			return err
		}))

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

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

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

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

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

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

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

	o.copyMatchingRows(o2...)

	return nil
}

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

func (os PublicreportQuickSlice) Organization(mods ...bob.Mod[*dialect.SelectQuery]) OrganizationsQuery {
	pkOrganizationID := make(pgtypes.Array[null.Val[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)),
	)...)
}

// Images starts a query for related objects on publicreport.image
func (o *PublicreportQuick) Images(mods ...bob.Mod[*dialect.SelectQuery]) PublicreportImagesQuery {
	return PublicreportImages.Query(append(mods,
		sm.InnerJoin(PublicreportQuickImages.NameAs()).On(
			PublicreportImages.Columns.ID.EQ(PublicreportQuickImages.Columns.ImageID)),
		sm.Where(PublicreportQuickImages.Columns.QuickID.EQ(psql.Arg(o.ID))),
	)...)
}

func (os PublicreportQuickSlice) Images(mods ...bob.Mod[*dialect.SelectQuery]) PublicreportImagesQuery {
	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 PublicreportImages.Query(append(mods,
		sm.InnerJoin(PublicreportQuickImages.NameAs()).On(
			PublicreportImages.Columns.ID.EQ(PublicreportQuickImages.Columns.ImageID),
		),
		sm.Where(psql.Group(PublicreportQuickImages.Columns.QuickID).OP("IN", PKArgExpr)),
	)...)
}

func attachPublicreportQuickOrganization0(ctx context.Context, exec bob.Executor, count int, publicreportQuick0 *PublicreportQuick, organization1 *Organization) (*PublicreportQuick, error) {
	setter := &PublicreportQuickSetter{
		OrganizationID: omitnull.From(organization1.ID),
	}

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

	return publicreportQuick0, nil
}

func (publicreportQuick0 *PublicreportQuick) 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 = attachPublicreportQuickOrganization0(ctx, exec, 1, publicreportQuick0, organization1)
	if err != nil {
		return err
	}

	publicreportQuick0.R.Organization = organization1

	organization1.R.Quicks = append(organization1.R.Quicks, publicreportQuick0)

	return nil
}

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

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

	publicreportQuick0.R.Organization = organization1

	organization1.R.Quicks = append(organization1.R.Quicks, publicreportQuick0)

	return nil
}

func attachPublicreportQuickImages0(ctx context.Context, exec bob.Executor, count int, publicreportQuick0 *PublicreportQuick, publicreportImages2 PublicreportImageSlice) (PublicreportQuickImageSlice, error) {
	setters := make([]*PublicreportQuickImageSetter, count)
	for i := range count {
		setters[i] = &PublicreportQuickImageSetter{
			QuickID: omit.From(publicreportQuick0.ID),
			ImageID: omit.From(publicreportImages2[i].ID),
		}
	}

	publicreportQuickImages1, err := PublicreportQuickImages.Insert(bob.ToMods(setters...)).All(ctx, exec)
	if err != nil {
		return nil, fmt.Errorf("attachPublicreportQuickImages0: %w", err)
	}

	return publicreportQuickImages1, nil
}

func (publicreportQuick0 *PublicreportQuick) InsertImages(ctx context.Context, exec bob.Executor, related ...*PublicreportImageSetter) error {
	if len(related) == 0 {
		return nil
	}

	var err error

	inserted, err := PublicreportImages.Insert(bob.ToMods(related...)).All(ctx, exec)
	if err != nil {
		return fmt.Errorf("inserting related objects: %w", err)
	}
	publicreportImages2 := PublicreportImageSlice(inserted)

	_, err = attachPublicreportQuickImages0(ctx, exec, len(related), publicreportQuick0, publicreportImages2)
	if err != nil {
		return err
	}

	publicreportQuick0.R.Images = append(publicreportQuick0.R.Images, publicreportImages2...)

	for _, rel := range publicreportImages2 {
		rel.R.Quicks = append(rel.R.Quicks, publicreportQuick0)
	}
	return nil
}

func (publicreportQuick0 *PublicreportQuick) AttachImages(ctx context.Context, exec bob.Executor, related ...*PublicreportImage) error {
	if len(related) == 0 {
		return nil
	}

	var err error
	publicreportImages2 := PublicreportImageSlice(related)

	_, err = attachPublicreportQuickImages0(ctx, exec, len(related), publicreportQuick0, publicreportImages2)
	if err != nil {
		return err
	}

	publicreportQuick0.R.Images = append(publicreportQuick0.R.Images, publicreportImages2...)

	for _, rel := range related {
		rel.R.Quicks = append(rel.R.Quicks, publicreportQuick0)
	}

	return nil
}

type publicreportQuickWhere[Q psql.Filterable] struct {
	ID             psql.WhereMod[Q, int32]
	Created        psql.WhereMod[Q, time.Time]
	Comments       psql.WhereMod[Q, string]
	Location       psql.WhereNullMod[Q, string]
	H3cell         psql.WhereNullMod[Q, string]
	PublicID       psql.WhereMod[Q, string]
	ReporterEmail  psql.WhereMod[Q, string]
	ReporterPhone  psql.WhereMod[Q, string]
	Address        psql.WhereMod[Q, string]
	Status         psql.WhereMod[Q, enums.PublicreportReportstatustype]
	OrganizationID psql.WhereNullMod[Q, int32]
}

func (publicreportQuickWhere[Q]) AliasedAs(alias string) publicreportQuickWhere[Q] {
	return buildPublicreportQuickWhere[Q](buildPublicreportQuickColumns(alias))
}

func buildPublicreportQuickWhere[Q psql.Filterable](cols publicreportQuickColumns) publicreportQuickWhere[Q] {
	return publicreportQuickWhere[Q]{
		ID:             psql.Where[Q, int32](cols.ID),
		Created:        psql.Where[Q, time.Time](cols.Created),
		Comments:       psql.Where[Q, string](cols.Comments),
		Location:       psql.WhereNull[Q, string](cols.Location),
		H3cell:         psql.WhereNull[Q, string](cols.H3cell),
		PublicID:       psql.Where[Q, string](cols.PublicID),
		ReporterEmail:  psql.Where[Q, string](cols.ReporterEmail),
		ReporterPhone:  psql.Where[Q, string](cols.ReporterPhone),
		Address:        psql.Where[Q, string](cols.Address),
		Status:         psql.Where[Q, enums.PublicreportReportstatustype](cols.Status),
		OrganizationID: psql.WhereNull[Q, int32](cols.OrganizationID),
	}
}

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

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

		o.R.Organization = rel

		if rel != nil {
			rel.R.Quicks = PublicreportQuickSlice{o}
		}
		return nil
	case "Images":
		rels, ok := retrieved.(PublicreportImageSlice)
		if !ok {
			return fmt.Errorf("publicreportQuick cannot load %T as %q", retrieved, name)
		}

		o.R.Images = rels

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

type publicreportQuickPreloader struct {
	Organization func(...psql.PreloadOption) psql.Preloader
}

func buildPublicreportQuickPreloader() publicreportQuickPreloader {
	return publicreportQuickPreloader{
		Organization: func(opts ...psql.PreloadOption) psql.Preloader {
			return psql.Preload[*Organization, OrganizationSlice](psql.PreloadRel{
				Name: "Organization",
				Sides: []psql.PreloadSide{
					{
						From:        PublicreportQuicks,
						To:          Organizations,
						FromColumns: []string{"organization_id"},
						ToColumns:   []string{"id"},
					},
				},
			}, Organizations.Columns.Names(), opts...)
		},
	}
}

type publicreportQuickThenLoader[Q orm.Loadable] struct {
	Organization func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q]
	Images       func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q]
}

func buildPublicreportQuickThenLoader[Q orm.Loadable]() publicreportQuickThenLoader[Q] {
	type OrganizationLoadInterface interface {
		LoadOrganization(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error
	}
	type ImagesLoadInterface interface {
		LoadImages(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error
	}

	return publicreportQuickThenLoader[Q]{
		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...)
			},
		),
		Images: thenLoadBuilder[Q](
			"Images",
			func(ctx context.Context, exec bob.Executor, retrieved ImagesLoadInterface, mods ...bob.Mod[*dialect.SelectQuery]) error {
				return retrieved.LoadImages(ctx, exec, mods...)
			},
		),
	}
}

// LoadOrganization loads the publicreportQuick's Organization into the .R struct
func (o *PublicreportQuick) 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.Quicks = PublicreportQuickSlice{o}

	o.R.Organization = related
	return nil
}

// LoadOrganization loads the publicreportQuick's Organization into the .R struct
func (os PublicreportQuickSlice) 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.IsValue() {
				continue
			}

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

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

			o.R.Organization = rel
			break
		}
	}

	return nil
}

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

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

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

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

	o.R.Images = related
	return nil
}

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

	// since we are changing the columns, we need to check if the original columns were set or add the defaults
	sq := dialect.SelectQuery{}
	for _, mod := range mods {
		mod.Apply(&sq)
	}

	if len(sq.SelectList.Columns) == 0 {
		mods = append(mods, sm.Columns(PublicreportImages.Columns))
	}

	q := os.Images(append(
		mods,
		sm.Columns(PublicreportQuickImages.Columns.QuickID.As("related_publicreport.quick.ID")),
	)...)

	IDSlice := []int32{}

	mapper := scan.Mod(scan.StructMapper[*PublicreportImage](), func(ctx context.Context, cols []string) (scan.BeforeFunc, func(any, any) error) {
		return func(row *scan.Row) (any, error) {
				IDSlice = append(IDSlice, *new(int32))
				row.ScheduleScanByName("related_publicreport.quick.ID", &IDSlice[len(IDSlice)-1])

				return nil, nil
			},
			func(any, any) error {
				return nil
			}
	})

	publicreportImages, err := bob.Allx[bob.SliceTransformer[*PublicreportImage, PublicreportImageSlice]](ctx, exec, q, mapper)
	if err != nil {
		return err
	}

	for _, o := range os {
		o.R.Images = nil
	}

	for _, o := range os {
		for i, rel := range publicreportImages {
			if !(o.ID == IDSlice[i]) {
				continue
			}

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

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

	return nil
}

// publicreportQuickC is where relationship counts are stored.
type publicreportQuickC struct {
	Images *int64
}

// PreloadCount sets a count in the C struct by name
func (o *PublicreportQuick) PreloadCount(name string, count int64) error {
	if o == nil {
		return nil
	}

	switch name {
	case "Images":
		o.C.Images = &count
	}
	return nil
}

type publicreportQuickCountPreloader struct {
	Images func(...bob.Mod[*dialect.SelectQuery]) psql.Preloader
}

func buildPublicreportQuickCountPreloader() publicreportQuickCountPreloader {
	return publicreportQuickCountPreloader{
		Images: func(mods ...bob.Mod[*dialect.SelectQuery]) psql.Preloader {
			return countPreloader[*PublicreportQuick]("Images", func(parent string) bob.Expression {
				// Build a correlated subquery: (SELECT COUNT(*) FROM related WHERE fk = parent.pk)
				if parent == "" {
					parent = PublicreportQuicks.Alias()
				}

				subqueryMods := []bob.Mod[*dialect.SelectQuery]{
					sm.Columns(psql.Raw("count(*)")),

					sm.From(PublicreportQuickImages.Name()),
					sm.Where(psql.Quote(PublicreportQuickImages.Alias(), "quick_id").EQ(psql.Quote(parent, "id"))),
					sm.InnerJoin(PublicreportImages.Name()).On(
						psql.Quote(PublicreportImages.Alias(), "id").EQ(psql.Quote(PublicreportQuickImages.Alias(), "image_id")),
					),
				}
				subqueryMods = append(subqueryMods, mods...)
				return psql.Group(psql.Select(subqueryMods...).Expression)
			})
		},
	}
}

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

func buildPublicreportQuickCountThenLoader[Q orm.Loadable]() publicreportQuickCountThenLoader[Q] {
	type ImagesCountInterface interface {
		LoadCountImages(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error
	}

	return publicreportQuickCountThenLoader[Q]{
		Images: countThenLoadBuilder[Q](
			"Images",
			func(ctx context.Context, exec bob.Executor, retrieved ImagesCountInterface, mods ...bob.Mod[*dialect.SelectQuery]) error {
				return retrieved.LoadCountImages(ctx, exec, mods...)
			},
		),
	}
}

// LoadCountImages loads the count of Images into the C struct
func (o *PublicreportQuick) LoadCountImages(ctx context.Context, exec bob.Executor, mods ...bob.Mod[*dialect.SelectQuery]) error {
	if o == nil {
		return nil
	}

	count, err := o.Images(mods...).Count(ctx, exec)
	if err != nil {
		return err
	}

	o.C.Images = &count
	return nil
}

// LoadCountImages loads the count of Images for a slice
func (os PublicreportQuickSlice) LoadCountImages(ctx context.Context, exec bob.Executor, mods ...bob.Mod[*dialect.SelectQuery]) error {
	if len(os) == 0 {
		return nil
	}

	for _, o := range os {
		if err := o.LoadCountImages(ctx, exec, mods...); err != nil {
			return err
		}
	}

	return nil
}

type publicreportQuickJoins[Q dialect.Joinable] struct {
	typ          string
	Organization modAs[Q, organizationColumns]
	Images       modAs[Q, publicreportImageColumns]
}

func (j publicreportQuickJoins[Q]) aliasedAs(alias string) publicreportQuickJoins[Q] {
	return buildPublicreportQuickJoins[Q](buildPublicreportQuickColumns(alias), j.typ)
}

func buildPublicreportQuickJoins[Q dialect.Joinable](cols publicreportQuickColumns, typ string) publicreportQuickJoins[Q] {
	return publicreportQuickJoins[Q]{
		typ: typ,
		Organization: modAs[Q, organizationColumns]{
			c: Organizations.Columns,
			f: func(to organizationColumns) bob.Mod[Q] {
				mods := make(mods.QueryMods[Q], 0, 1)

				{
					mods = append(mods, dialect.Join[Q](typ, Organizations.Name().As(to.Alias())).On(
						to.ID.EQ(cols.OrganizationID),
					))
				}

				return mods
			},
		},
		Images: modAs[Q, publicreportImageColumns]{
			c: PublicreportImages.Columns,
			f: func(to publicreportImageColumns) bob.Mod[Q] {
				random := strconv.FormatInt(randInt(), 10)
				mods := make(mods.QueryMods[Q], 0, 2)

				{
					to := PublicreportQuickImages.Columns.AliasedAs(PublicreportQuickImages.Columns.Alias() + random)
					mods = append(mods, dialect.Join[Q](typ, PublicreportQuickImages.Name().As(to.Alias())).On(
						to.QuickID.EQ(cols.ID),
					))
				}
				{
					cols := PublicreportQuickImages.Columns.AliasedAs(PublicreportQuickImages.Columns.Alias() + random)
					mods = append(mods, dialect.Join[Q](typ, PublicreportImages.Name().As(to.Alias())).On(
						to.ID.EQ(cols.ImageID),
					))
				}

				return mods
			},
		},
	}
}
