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

	"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/omit"
	enums "source.gleipnir.technology/Gleipnir/nidus-sync/db/enums"
)

// PublicreportWater is an object representing the database table.
type PublicreportWater struct {
	AccessComments         string                                 `db:"access_comments" `
	AccessGate             bool                                   `db:"access_gate" `
	AccessFence            bool                                   `db:"access_fence" `
	AccessLocked           bool                                   `db:"access_locked" `
	AccessDog              bool                                   `db:"access_dog" `
	AccessOther            bool                                   `db:"access_other" `
	Comments               string                                 `db:"comments" `
	IsReporterConfidential bool                                   `db:"is_reporter_confidential" `
	IsReporterOwner        bool                                   `db:"is_reporter_owner" `
	HasAdult               bool                                   `db:"has_adult" `
	HasBackyardPermission  bool                                   `db:"has_backyard_permission" `
	HasLarvae              bool                                   `db:"has_larvae" `
	HasPupae               bool                                   `db:"has_pupae" `
	OwnerEmail             string                                 `db:"owner_email" `
	OwnerName              string                                 `db:"owner_name" `
	OwnerPhone             string                                 `db:"owner_phone" `
	ReportID               int32                                  `db:"report_id,pk" `
	Duration               enums.PublicreportNuisancedurationtype `db:"duration" `

	R publicreportWaterR `db:"-" `
}

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

// PublicreportWaters contains methods to work with the water table
var PublicreportWaters = psql.NewTablex[*PublicreportWater, PublicreportWaterSlice, *PublicreportWaterSetter]("publicreport", "water", buildPublicreportWaterColumns("publicreport.water"))

// PublicreportWatersQuery is a query on the water table
type PublicreportWatersQuery = *psql.ViewQuery[*PublicreportWater, PublicreportWaterSlice]

// publicreportWaterR is where relationships are stored.
type publicreportWaterR struct {
	Report *PublicreportReport // publicreport.water.water_report_id_fkey
}

func buildPublicreportWaterColumns(alias string) publicreportWaterColumns {
	return publicreportWaterColumns{
		ColumnsExpr: expr.NewColumnsExpr(
			"access_comments", "access_gate", "access_fence", "access_locked", "access_dog", "access_other", "comments", "is_reporter_confidential", "is_reporter_owner", "has_adult", "has_backyard_permission", "has_larvae", "has_pupae", "owner_email", "owner_name", "owner_phone", "report_id", "duration",
		).WithParent("publicreport.water"),
		tableAlias:             alias,
		AccessComments:         psql.Quote(alias, "access_comments"),
		AccessGate:             psql.Quote(alias, "access_gate"),
		AccessFence:            psql.Quote(alias, "access_fence"),
		AccessLocked:           psql.Quote(alias, "access_locked"),
		AccessDog:              psql.Quote(alias, "access_dog"),
		AccessOther:            psql.Quote(alias, "access_other"),
		Comments:               psql.Quote(alias, "comments"),
		IsReporterConfidential: psql.Quote(alias, "is_reporter_confidential"),
		IsReporterOwner:        psql.Quote(alias, "is_reporter_owner"),
		HasAdult:               psql.Quote(alias, "has_adult"),
		HasBackyardPermission:  psql.Quote(alias, "has_backyard_permission"),
		HasLarvae:              psql.Quote(alias, "has_larvae"),
		HasPupae:               psql.Quote(alias, "has_pupae"),
		OwnerEmail:             psql.Quote(alias, "owner_email"),
		OwnerName:              psql.Quote(alias, "owner_name"),
		OwnerPhone:             psql.Quote(alias, "owner_phone"),
		ReportID:               psql.Quote(alias, "report_id"),
		Duration:               psql.Quote(alias, "duration"),
	}
}

type publicreportWaterColumns struct {
	expr.ColumnsExpr
	tableAlias             string
	AccessComments         psql.Expression
	AccessGate             psql.Expression
	AccessFence            psql.Expression
	AccessLocked           psql.Expression
	AccessDog              psql.Expression
	AccessOther            psql.Expression
	Comments               psql.Expression
	IsReporterConfidential psql.Expression
	IsReporterOwner        psql.Expression
	HasAdult               psql.Expression
	HasBackyardPermission  psql.Expression
	HasLarvae              psql.Expression
	HasPupae               psql.Expression
	OwnerEmail             psql.Expression
	OwnerName              psql.Expression
	OwnerPhone             psql.Expression
	ReportID               psql.Expression
	Duration               psql.Expression
}

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

func (publicreportWaterColumns) AliasedAs(alias string) publicreportWaterColumns {
	return buildPublicreportWaterColumns(alias)
}

// PublicreportWaterSetter is used for insert/upsert/update operations
// All values are optional, and do not have to be set
// Generated columns are not included
type PublicreportWaterSetter struct {
	AccessComments         omit.Val[string]                                 `db:"access_comments" `
	AccessGate             omit.Val[bool]                                   `db:"access_gate" `
	AccessFence            omit.Val[bool]                                   `db:"access_fence" `
	AccessLocked           omit.Val[bool]                                   `db:"access_locked" `
	AccessDog              omit.Val[bool]                                   `db:"access_dog" `
	AccessOther            omit.Val[bool]                                   `db:"access_other" `
	Comments               omit.Val[string]                                 `db:"comments" `
	IsReporterConfidential omit.Val[bool]                                   `db:"is_reporter_confidential" `
	IsReporterOwner        omit.Val[bool]                                   `db:"is_reporter_owner" `
	HasAdult               omit.Val[bool]                                   `db:"has_adult" `
	HasBackyardPermission  omit.Val[bool]                                   `db:"has_backyard_permission" `
	HasLarvae              omit.Val[bool]                                   `db:"has_larvae" `
	HasPupae               omit.Val[bool]                                   `db:"has_pupae" `
	OwnerEmail             omit.Val[string]                                 `db:"owner_email" `
	OwnerName              omit.Val[string]                                 `db:"owner_name" `
	OwnerPhone             omit.Val[string]                                 `db:"owner_phone" `
	ReportID               omit.Val[int32]                                  `db:"report_id,pk" `
	Duration               omit.Val[enums.PublicreportNuisancedurationtype] `db:"duration" `
}

func (s PublicreportWaterSetter) SetColumns() []string {
	vals := make([]string, 0, 18)
	if s.AccessComments.IsValue() {
		vals = append(vals, "access_comments")
	}
	if s.AccessGate.IsValue() {
		vals = append(vals, "access_gate")
	}
	if s.AccessFence.IsValue() {
		vals = append(vals, "access_fence")
	}
	if s.AccessLocked.IsValue() {
		vals = append(vals, "access_locked")
	}
	if s.AccessDog.IsValue() {
		vals = append(vals, "access_dog")
	}
	if s.AccessOther.IsValue() {
		vals = append(vals, "access_other")
	}
	if s.Comments.IsValue() {
		vals = append(vals, "comments")
	}
	if s.IsReporterConfidential.IsValue() {
		vals = append(vals, "is_reporter_confidential")
	}
	if s.IsReporterOwner.IsValue() {
		vals = append(vals, "is_reporter_owner")
	}
	if s.HasAdult.IsValue() {
		vals = append(vals, "has_adult")
	}
	if s.HasBackyardPermission.IsValue() {
		vals = append(vals, "has_backyard_permission")
	}
	if s.HasLarvae.IsValue() {
		vals = append(vals, "has_larvae")
	}
	if s.HasPupae.IsValue() {
		vals = append(vals, "has_pupae")
	}
	if s.OwnerEmail.IsValue() {
		vals = append(vals, "owner_email")
	}
	if s.OwnerName.IsValue() {
		vals = append(vals, "owner_name")
	}
	if s.OwnerPhone.IsValue() {
		vals = append(vals, "owner_phone")
	}
	if s.ReportID.IsValue() {
		vals = append(vals, "report_id")
	}
	if s.Duration.IsValue() {
		vals = append(vals, "duration")
	}
	return vals
}

func (s PublicreportWaterSetter) Overwrite(t *PublicreportWater) {
	if s.AccessComments.IsValue() {
		t.AccessComments = s.AccessComments.MustGet()
	}
	if s.AccessGate.IsValue() {
		t.AccessGate = s.AccessGate.MustGet()
	}
	if s.AccessFence.IsValue() {
		t.AccessFence = s.AccessFence.MustGet()
	}
	if s.AccessLocked.IsValue() {
		t.AccessLocked = s.AccessLocked.MustGet()
	}
	if s.AccessDog.IsValue() {
		t.AccessDog = s.AccessDog.MustGet()
	}
	if s.AccessOther.IsValue() {
		t.AccessOther = s.AccessOther.MustGet()
	}
	if s.Comments.IsValue() {
		t.Comments = s.Comments.MustGet()
	}
	if s.IsReporterConfidential.IsValue() {
		t.IsReporterConfidential = s.IsReporterConfidential.MustGet()
	}
	if s.IsReporterOwner.IsValue() {
		t.IsReporterOwner = s.IsReporterOwner.MustGet()
	}
	if s.HasAdult.IsValue() {
		t.HasAdult = s.HasAdult.MustGet()
	}
	if s.HasBackyardPermission.IsValue() {
		t.HasBackyardPermission = s.HasBackyardPermission.MustGet()
	}
	if s.HasLarvae.IsValue() {
		t.HasLarvae = s.HasLarvae.MustGet()
	}
	if s.HasPupae.IsValue() {
		t.HasPupae = s.HasPupae.MustGet()
	}
	if s.OwnerEmail.IsValue() {
		t.OwnerEmail = s.OwnerEmail.MustGet()
	}
	if s.OwnerName.IsValue() {
		t.OwnerName = s.OwnerName.MustGet()
	}
	if s.OwnerPhone.IsValue() {
		t.OwnerPhone = s.OwnerPhone.MustGet()
	}
	if s.ReportID.IsValue() {
		t.ReportID = s.ReportID.MustGet()
	}
	if s.Duration.IsValue() {
		t.Duration = s.Duration.MustGet()
	}
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

	return exprs
}

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

	return PublicreportWaters.Query(
		sm.Where(PublicreportWaters.Columns.ReportID.EQ(psql.Arg(ReportIDPK))),
		sm.Columns(PublicreportWaters.Columns.Only(cols...)),
	).One(ctx, exec)
}

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

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

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

	return err
}

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

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

// Reload refreshes the PublicreportWater using the executor
func (o *PublicreportWater) Reload(ctx context.Context, exec bob.Executor) error {
	o2, err := PublicreportWaters.Query(
		sm.Where(PublicreportWaters.Columns.ReportID.EQ(psql.Arg(o.ReportID))),
	).One(ctx, exec)
	if err != nil {
		return err
	}
	o2.R = o.R
	*o = *o2

	return nil
}

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

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

	return err
}

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

	return psql.Quote("publicreport.water", "report_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 PublicreportWaterSlice) copyMatchingRows(from ...*PublicreportWater) {
	for i, old := range o {
		for _, new := range from {
			if new.ReportID != old.ReportID {
				continue
			}
			new.R = old.R
			o[i] = new
			break
		}
	}
}

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

			return err
		}))

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

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

			return err
		}))

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

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

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

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

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

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

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

	o.copyMatchingRows(o2...)

	return nil
}

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

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

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

func attachPublicreportWaterReport0(ctx context.Context, exec bob.Executor, count int, publicreportWater0 *PublicreportWater, publicreportReport1 *PublicreportReport) (*PublicreportWater, error) {
	setter := &PublicreportWaterSetter{
		ReportID: omit.From(publicreportReport1.ID),
	}

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

	return publicreportWater0, nil
}

func (publicreportWater0 *PublicreportWater) InsertReport(ctx context.Context, exec bob.Executor, related *PublicreportReportSetter) error {
	var err error

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

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

	publicreportWater0.R.Report = publicreportReport1

	publicreportReport1.R.Water = publicreportWater0

	return nil
}

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

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

	publicreportWater0.R.Report = publicreportReport1

	publicreportReport1.R.Water = publicreportWater0

	return nil
}

type publicreportWaterWhere[Q psql.Filterable] struct {
	AccessComments         psql.WhereMod[Q, string]
	AccessGate             psql.WhereMod[Q, bool]
	AccessFence            psql.WhereMod[Q, bool]
	AccessLocked           psql.WhereMod[Q, bool]
	AccessDog              psql.WhereMod[Q, bool]
	AccessOther            psql.WhereMod[Q, bool]
	Comments               psql.WhereMod[Q, string]
	IsReporterConfidential psql.WhereMod[Q, bool]
	IsReporterOwner        psql.WhereMod[Q, bool]
	HasAdult               psql.WhereMod[Q, bool]
	HasBackyardPermission  psql.WhereMod[Q, bool]
	HasLarvae              psql.WhereMod[Q, bool]
	HasPupae               psql.WhereMod[Q, bool]
	OwnerEmail             psql.WhereMod[Q, string]
	OwnerName              psql.WhereMod[Q, string]
	OwnerPhone             psql.WhereMod[Q, string]
	ReportID               psql.WhereMod[Q, int32]
	Duration               psql.WhereMod[Q, enums.PublicreportNuisancedurationtype]
}

func (publicreportWaterWhere[Q]) AliasedAs(alias string) publicreportWaterWhere[Q] {
	return buildPublicreportWaterWhere[Q](buildPublicreportWaterColumns(alias))
}

func buildPublicreportWaterWhere[Q psql.Filterable](cols publicreportWaterColumns) publicreportWaterWhere[Q] {
	return publicreportWaterWhere[Q]{
		AccessComments:         psql.Where[Q, string](cols.AccessComments),
		AccessGate:             psql.Where[Q, bool](cols.AccessGate),
		AccessFence:            psql.Where[Q, bool](cols.AccessFence),
		AccessLocked:           psql.Where[Q, bool](cols.AccessLocked),
		AccessDog:              psql.Where[Q, bool](cols.AccessDog),
		AccessOther:            psql.Where[Q, bool](cols.AccessOther),
		Comments:               psql.Where[Q, string](cols.Comments),
		IsReporterConfidential: psql.Where[Q, bool](cols.IsReporterConfidential),
		IsReporterOwner:        psql.Where[Q, bool](cols.IsReporterOwner),
		HasAdult:               psql.Where[Q, bool](cols.HasAdult),
		HasBackyardPermission:  psql.Where[Q, bool](cols.HasBackyardPermission),
		HasLarvae:              psql.Where[Q, bool](cols.HasLarvae),
		HasPupae:               psql.Where[Q, bool](cols.HasPupae),
		OwnerEmail:             psql.Where[Q, string](cols.OwnerEmail),
		OwnerName:              psql.Where[Q, string](cols.OwnerName),
		OwnerPhone:             psql.Where[Q, string](cols.OwnerPhone),
		ReportID:               psql.Where[Q, int32](cols.ReportID),
		Duration:               psql.Where[Q, enums.PublicreportNuisancedurationtype](cols.Duration),
	}
}

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

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

		o.R.Report = rel

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

type publicreportWaterPreloader struct {
	Report func(...psql.PreloadOption) psql.Preloader
}

func buildPublicreportWaterPreloader() publicreportWaterPreloader {
	return publicreportWaterPreloader{
		Report: func(opts ...psql.PreloadOption) psql.Preloader {
			return psql.Preload[*PublicreportReport, PublicreportReportSlice](psql.PreloadRel{
				Name: "Report",
				Sides: []psql.PreloadSide{
					{
						From:        PublicreportWaters,
						To:          PublicreportReports,
						FromColumns: []string{"report_id"},
						ToColumns:   []string{"id"},
					},
				},
			}, PublicreportReports.Columns.Names(), opts...)
		},
	}
}

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

func buildPublicreportWaterThenLoader[Q orm.Loadable]() publicreportWaterThenLoader[Q] {
	type ReportLoadInterface interface {
		LoadReport(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error
	}

	return publicreportWaterThenLoader[Q]{
		Report: thenLoadBuilder[Q](
			"Report",
			func(ctx context.Context, exec bob.Executor, retrieved ReportLoadInterface, mods ...bob.Mod[*dialect.SelectQuery]) error {
				return retrieved.LoadReport(ctx, exec, mods...)
			},
		),
	}
}

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

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

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

	related.R.Water = o

	o.R.Report = related
	return nil
}

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

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

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

		for _, rel := range publicreportReports {

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

			rel.R.Water = o

			o.R.Report = rel
			break
		}
	}

	return nil
}
