// 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/null"
	"github.com/aarondl/opt/omit"
	"github.com/aarondl/opt/omitnull"
)

// Parcel is an object representing the database table.
type Parcel struct {
	Apn         null.Val[string] `db:"apn" `
	Description null.Val[string] `db:"description" `
	ID          int32            `db:"id,pk" `
	Geometry    string           `db:"geometry" `

	R parcelR `db:"-" `
}

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

// Parcels contains methods to work with the parcel table
var Parcels = psql.NewTablex[*Parcel, ParcelSlice, *ParcelSetter]("", "parcel", buildParcelColumns("parcel"))

// ParcelsQuery is a query on the parcel table
type ParcelsQuery = *psql.ViewQuery[*Parcel, ParcelSlice]

// parcelR is where relationships are stored.
type parcelR struct {
	Sites SiteSlice // site.site_parcel_id_fkey
}

func buildParcelColumns(alias string) parcelColumns {
	return parcelColumns{
		ColumnsExpr: expr.NewColumnsExpr(
			"apn", "description", "id", "geometry",
		).WithParent("parcel"),
		tableAlias:  alias,
		Apn:         psql.Quote(alias, "apn"),
		Description: psql.Quote(alias, "description"),
		ID:          psql.Quote(alias, "id"),
		Geometry:    psql.Quote(alias, "geometry"),
	}
}

type parcelColumns struct {
	expr.ColumnsExpr
	tableAlias  string
	Apn         psql.Expression
	Description psql.Expression
	ID          psql.Expression
	Geometry    psql.Expression
}

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

func (parcelColumns) AliasedAs(alias string) parcelColumns {
	return buildParcelColumns(alias)
}

// ParcelSetter is used for insert/upsert/update operations
// All values are optional, and do not have to be set
// Generated columns are not included
type ParcelSetter struct {
	Apn         omitnull.Val[string] `db:"apn" `
	Description omitnull.Val[string] `db:"description" `
	ID          omit.Val[int32]      `db:"id,pk" `
	Geometry    omit.Val[string]     `db:"geometry" `
}

func (s ParcelSetter) SetColumns() []string {
	vals := make([]string, 0, 4)
	if !s.Apn.IsUnset() {
		vals = append(vals, "apn")
	}
	if !s.Description.IsUnset() {
		vals = append(vals, "description")
	}
	if s.ID.IsValue() {
		vals = append(vals, "id")
	}
	if s.Geometry.IsValue() {
		vals = append(vals, "geometry")
	}
	return vals
}

func (s ParcelSetter) Overwrite(t *Parcel) {
	if !s.Apn.IsUnset() {
		t.Apn = s.Apn.MustGetNull()
	}
	if !s.Description.IsUnset() {
		t.Description = s.Description.MustGetNull()
	}
	if s.ID.IsValue() {
		t.ID = s.ID.MustGet()
	}
	if s.Geometry.IsValue() {
		t.Geometry = s.Geometry.MustGet()
	}
}

func (s *ParcelSetter) Apply(q *dialect.InsertQuery) {
	q.AppendHooks(func(ctx context.Context, exec bob.Executor) (context.Context, error) {
		return Parcels.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, 4)
		if !s.Apn.IsUnset() {
			vals[0] = psql.Arg(s.Apn.MustGetNull())
		} else {
			vals[0] = psql.Raw("DEFAULT")
		}

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

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

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

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

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

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

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

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

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

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

	return exprs
}

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

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

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

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

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

	return err
}

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

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

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

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

	return err
}

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

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

			return err
		}))

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

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

			return err
		}))

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

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

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

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

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

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

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

	o.copyMatchingRows(o2...)

	return nil
}

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

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

func insertParcelSites0(ctx context.Context, exec bob.Executor, sites1 []*SiteSetter, parcel0 *Parcel) (SiteSlice, error) {
	for i := range sites1 {
		sites1[i].ParcelID = omitnull.From(parcel0.ID)
	}

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

	return ret, nil
}

func attachParcelSites0(ctx context.Context, exec bob.Executor, count int, sites1 SiteSlice, parcel0 *Parcel) (SiteSlice, error) {
	setter := &SiteSetter{
		ParcelID: omitnull.From(parcel0.ID),
	}

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

	return sites1, nil
}

func (parcel0 *Parcel) InsertSites(ctx context.Context, exec bob.Executor, related ...*SiteSetter) error {
	if len(related) == 0 {
		return nil
	}

	var err error

	sites1, err := insertParcelSites0(ctx, exec, related, parcel0)
	if err != nil {
		return err
	}

	parcel0.R.Sites = append(parcel0.R.Sites, sites1...)

	for _, rel := range sites1 {
		rel.R.Parcel = parcel0
	}
	return nil
}

func (parcel0 *Parcel) AttachSites(ctx context.Context, exec bob.Executor, related ...*Site) error {
	if len(related) == 0 {
		return nil
	}

	var err error
	sites1 := SiteSlice(related)

	_, err = attachParcelSites0(ctx, exec, len(related), sites1, parcel0)
	if err != nil {
		return err
	}

	parcel0.R.Sites = append(parcel0.R.Sites, sites1...)

	for _, rel := range related {
		rel.R.Parcel = parcel0
	}

	return nil
}

type parcelWhere[Q psql.Filterable] struct {
	Apn         psql.WhereNullMod[Q, string]
	Description psql.WhereNullMod[Q, string]
	ID          psql.WhereMod[Q, int32]
	Geometry    psql.WhereMod[Q, string]
}

func (parcelWhere[Q]) AliasedAs(alias string) parcelWhere[Q] {
	return buildParcelWhere[Q](buildParcelColumns(alias))
}

func buildParcelWhere[Q psql.Filterable](cols parcelColumns) parcelWhere[Q] {
	return parcelWhere[Q]{
		Apn:         psql.WhereNull[Q, string](cols.Apn),
		Description: psql.WhereNull[Q, string](cols.Description),
		ID:          psql.Where[Q, int32](cols.ID),
		Geometry:    psql.Where[Q, string](cols.Geometry),
	}
}

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

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

		o.R.Sites = rels

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

type parcelPreloader struct{}

func buildParcelPreloader() parcelPreloader {
	return parcelPreloader{}
}

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

func buildParcelThenLoader[Q orm.Loadable]() parcelThenLoader[Q] {
	type SitesLoadInterface interface {
		LoadSites(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error
	}

	return parcelThenLoader[Q]{
		Sites: thenLoadBuilder[Q](
			"Sites",
			func(ctx context.Context, exec bob.Executor, retrieved SitesLoadInterface, mods ...bob.Mod[*dialect.SelectQuery]) error {
				return retrieved.LoadSites(ctx, exec, mods...)
			},
		),
	}
}

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

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

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

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

	o.R.Sites = related
	return nil
}

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

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

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

		o.R.Sites = nil
	}

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

		for _, rel := range sites {

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

			rel.R.Parcel = o

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

	return nil
}
