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

// H3Aggregation is an object representing the database table.
type H3Aggregation struct {
	ID             int32                   `db:"id,pk" `
	Cell           string                  `db:"cell" `
	Count          int32                   `db:"count_" `
	Geometry       null.Val[string]        `db:"geometry" `
	OrganizationID int32                   `db:"organization_id" `
	Resolution     int32                   `db:"resolution" `
	Type           enums.H3aggregationtype `db:"type_" `

	R h3AggregationR `db:"-" `
}

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

// H3Aggregations contains methods to work with the h3_aggregation table
var H3Aggregations = psql.NewTablex[*H3Aggregation, H3AggregationSlice, *H3AggregationSetter]("", "h3_aggregation", buildH3AggregationColumns("h3_aggregation"))

// H3AggregationsQuery is a query on the h3_aggregation table
type H3AggregationsQuery = *psql.ViewQuery[*H3Aggregation, H3AggregationSlice]

// h3AggregationR is where relationships are stored.
type h3AggregationR struct {
	Organization *Organization // h3_aggregation.h3_aggregation_organization_id_fkey
}

func buildH3AggregationColumns(alias string) h3AggregationColumns {
	return h3AggregationColumns{
		ColumnsExpr: expr.NewColumnsExpr(
			"id", "cell", "count_", "geometry", "organization_id", "resolution", "type_",
		).WithParent("h3_aggregation"),
		tableAlias:     alias,
		ID:             psql.Quote(alias, "id"),
		Cell:           psql.Quote(alias, "cell"),
		Count:          psql.Quote(alias, "count_"),
		Geometry:       psql.Quote(alias, "geometry"),
		OrganizationID: psql.Quote(alias, "organization_id"),
		Resolution:     psql.Quote(alias, "resolution"),
		Type:           psql.Quote(alias, "type_"),
	}
}

type h3AggregationColumns struct {
	expr.ColumnsExpr
	tableAlias     string
	ID             psql.Expression
	Cell           psql.Expression
	Count          psql.Expression
	Geometry       psql.Expression
	OrganizationID psql.Expression
	Resolution     psql.Expression
	Type           psql.Expression
}

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

func (h3AggregationColumns) AliasedAs(alias string) h3AggregationColumns {
	return buildH3AggregationColumns(alias)
}

// H3AggregationSetter is used for insert/upsert/update operations
// All values are optional, and do not have to be set
// Generated columns are not included
type H3AggregationSetter struct {
	ID             omit.Val[int32]                   `db:"id,pk" `
	Cell           omit.Val[string]                  `db:"cell" `
	Count          omit.Val[int32]                   `db:"count_" `
	Geometry       omitnull.Val[string]              `db:"geometry" `
	OrganizationID omit.Val[int32]                   `db:"organization_id" `
	Resolution     omit.Val[int32]                   `db:"resolution" `
	Type           omit.Val[enums.H3aggregationtype] `db:"type_" `
}

func (s H3AggregationSetter) SetColumns() []string {
	vals := make([]string, 0, 7)
	if s.ID.IsValue() {
		vals = append(vals, "id")
	}
	if s.Cell.IsValue() {
		vals = append(vals, "cell")
	}
	if s.Count.IsValue() {
		vals = append(vals, "count_")
	}
	if !s.Geometry.IsUnset() {
		vals = append(vals, "geometry")
	}
	if s.OrganizationID.IsValue() {
		vals = append(vals, "organization_id")
	}
	if s.Resolution.IsValue() {
		vals = append(vals, "resolution")
	}
	if s.Type.IsValue() {
		vals = append(vals, "type_")
	}
	return vals
}

func (s H3AggregationSetter) Overwrite(t *H3Aggregation) {
	if s.ID.IsValue() {
		t.ID = s.ID.MustGet()
	}
	if s.Cell.IsValue() {
		t.Cell = s.Cell.MustGet()
	}
	if s.Count.IsValue() {
		t.Count = s.Count.MustGet()
	}
	if !s.Geometry.IsUnset() {
		t.Geometry = s.Geometry.MustGetNull()
	}
	if s.OrganizationID.IsValue() {
		t.OrganizationID = s.OrganizationID.MustGet()
	}
	if s.Resolution.IsValue() {
		t.Resolution = s.Resolution.MustGet()
	}
	if s.Type.IsValue() {
		t.Type = s.Type.MustGet()
	}
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

	return exprs
}

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

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

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

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

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

	return err
}

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

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

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

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

	return err
}

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

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

			return err
		}))

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

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

			return err
		}))

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

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

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

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

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

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

	o2, err := H3Aggregations.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 *H3Aggregation) Organization(mods ...bob.Mod[*dialect.SelectQuery]) OrganizationsQuery {
	return Organizations.Query(append(mods,
		sm.Where(Organizations.Columns.ID.EQ(psql.Arg(o.OrganizationID))),
	)...)
}

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

func attachH3AggregationOrganization0(ctx context.Context, exec bob.Executor, count int, h3Aggregation0 *H3Aggregation, organization1 *Organization) (*H3Aggregation, error) {
	setter := &H3AggregationSetter{
		OrganizationID: omit.From(organization1.ID),
	}

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

	return h3Aggregation0, nil
}

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

	h3Aggregation0.R.Organization = organization1

	organization1.R.H3Aggregations = append(organization1.R.H3Aggregations, h3Aggregation0)

	return nil
}

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

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

	h3Aggregation0.R.Organization = organization1

	organization1.R.H3Aggregations = append(organization1.R.H3Aggregations, h3Aggregation0)

	return nil
}

type h3AggregationWhere[Q psql.Filterable] struct {
	ID             psql.WhereMod[Q, int32]
	Cell           psql.WhereMod[Q, string]
	Count          psql.WhereMod[Q, int32]
	Geometry       psql.WhereNullMod[Q, string]
	OrganizationID psql.WhereMod[Q, int32]
	Resolution     psql.WhereMod[Q, int32]
	Type           psql.WhereMod[Q, enums.H3aggregationtype]
}

func (h3AggregationWhere[Q]) AliasedAs(alias string) h3AggregationWhere[Q] {
	return buildH3AggregationWhere[Q](buildH3AggregationColumns(alias))
}

func buildH3AggregationWhere[Q psql.Filterable](cols h3AggregationColumns) h3AggregationWhere[Q] {
	return h3AggregationWhere[Q]{
		ID:             psql.Where[Q, int32](cols.ID),
		Cell:           psql.Where[Q, string](cols.Cell),
		Count:          psql.Where[Q, int32](cols.Count),
		Geometry:       psql.WhereNull[Q, string](cols.Geometry),
		OrganizationID: psql.Where[Q, int32](cols.OrganizationID),
		Resolution:     psql.Where[Q, int32](cols.Resolution),
		Type:           psql.Where[Q, enums.H3aggregationtype](cols.Type),
	}
}

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

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

		o.R.Organization = rel

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

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

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

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

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

	return h3AggregationThenLoader[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...)
			},
		),
	}
}

// LoadOrganization loads the h3Aggregation's Organization into the .R struct
func (o *H3Aggregation) 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.H3Aggregations = H3AggregationSlice{o}

	o.R.Organization = related
	return nil
}

// LoadOrganization loads the h3Aggregation's Organization into the .R struct
func (os H3AggregationSlice) 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.H3Aggregations = append(rel.R.H3Aggregations, o)

			o.R.Organization = rel
			break
		}
	}

	return nil
}
