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

// SpatialRefSy is an object representing the database table.
type SpatialRefSy struct {
	Srid      int32            `db:"srid,pk" `
	AuthName  null.Val[string] `db:"auth_name" `
	AuthSrid  null.Val[int32]  `db:"auth_srid" `
	Srtext    null.Val[string] `db:"srtext" `
	Proj4text null.Val[string] `db:"proj4text" `
}

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

// SpatialRefSys contains methods to work with the spatial_ref_sys table
var SpatialRefSys = psql.NewTablex[*SpatialRefSy, SpatialRefSySlice, *SpatialRefSySetter]("", "spatial_ref_sys", buildSpatialRefSyColumns("spatial_ref_sys"))

// SpatialRefSysQuery is a query on the spatial_ref_sys table
type SpatialRefSysQuery = *psql.ViewQuery[*SpatialRefSy, SpatialRefSySlice]

func buildSpatialRefSyColumns(alias string) spatialRefSyColumns {
	return spatialRefSyColumns{
		ColumnsExpr: expr.NewColumnsExpr(
			"srid", "auth_name", "auth_srid", "srtext", "proj4text",
		).WithParent("spatial_ref_sys"),
		tableAlias: alias,
		Srid:       psql.Quote(alias, "srid"),
		AuthName:   psql.Quote(alias, "auth_name"),
		AuthSrid:   psql.Quote(alias, "auth_srid"),
		Srtext:     psql.Quote(alias, "srtext"),
		Proj4text:  psql.Quote(alias, "proj4text"),
	}
}

type spatialRefSyColumns struct {
	expr.ColumnsExpr
	tableAlias string
	Srid       psql.Expression
	AuthName   psql.Expression
	AuthSrid   psql.Expression
	Srtext     psql.Expression
	Proj4text  psql.Expression
}

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

func (spatialRefSyColumns) AliasedAs(alias string) spatialRefSyColumns {
	return buildSpatialRefSyColumns(alias)
}

// SpatialRefSySetter is used for insert/upsert/update operations
// All values are optional, and do not have to be set
// Generated columns are not included
type SpatialRefSySetter struct {
	Srid      omit.Val[int32]      `db:"srid,pk" `
	AuthName  omitnull.Val[string] `db:"auth_name" `
	AuthSrid  omitnull.Val[int32]  `db:"auth_srid" `
	Srtext    omitnull.Val[string] `db:"srtext" `
	Proj4text omitnull.Val[string] `db:"proj4text" `
}

func (s SpatialRefSySetter) SetColumns() []string {
	vals := make([]string, 0, 5)
	if s.Srid.IsValue() {
		vals = append(vals, "srid")
	}
	if !s.AuthName.IsUnset() {
		vals = append(vals, "auth_name")
	}
	if !s.AuthSrid.IsUnset() {
		vals = append(vals, "auth_srid")
	}
	if !s.Srtext.IsUnset() {
		vals = append(vals, "srtext")
	}
	if !s.Proj4text.IsUnset() {
		vals = append(vals, "proj4text")
	}
	return vals
}

func (s SpatialRefSySetter) Overwrite(t *SpatialRefSy) {
	if s.Srid.IsValue() {
		t.Srid = s.Srid.MustGet()
	}
	if !s.AuthName.IsUnset() {
		t.AuthName = s.AuthName.MustGetNull()
	}
	if !s.AuthSrid.IsUnset() {
		t.AuthSrid = s.AuthSrid.MustGetNull()
	}
	if !s.Srtext.IsUnset() {
		t.Srtext = s.Srtext.MustGetNull()
	}
	if !s.Proj4text.IsUnset() {
		t.Proj4text = s.Proj4text.MustGetNull()
	}
}

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

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

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

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

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

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

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

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

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

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

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

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

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

	return exprs
}

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

	return SpatialRefSys.Query(
		sm.Where(SpatialRefSys.Columns.Srid.EQ(psql.Arg(SridPK))),
		sm.Columns(SpatialRefSys.Columns.Only(cols...)),
	).One(ctx, exec)
}

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

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

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

	return err
}

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

func (o *SpatialRefSy) pkEQ() dialect.Expression {
	return psql.Quote("spatial_ref_sys", "srid").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 SpatialRefSy
func (o *SpatialRefSy) Update(ctx context.Context, exec bob.Executor, s *SpatialRefSySetter) error {
	v, err := SpatialRefSys.Update(s.UpdateMod(), um.Where(o.pkEQ())).One(ctx, exec)
	if err != nil {
		return err
	}

	*o = *v

	return nil
}

// Delete deletes a single SpatialRefSy record with an executor
func (o *SpatialRefSy) Delete(ctx context.Context, exec bob.Executor) error {
	_, err := SpatialRefSys.Delete(dm.Where(o.pkEQ())).Exec(ctx, exec)
	return err
}

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

	*o = *o2

	return nil
}

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

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

	return err
}

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

	return psql.Quote("spatial_ref_sys", "srid").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 SpatialRefSySlice) copyMatchingRows(from ...*SpatialRefSy) {
	for i, old := range o {
		for _, new := range from {
			if new.Srid != old.Srid {
				continue
			}

			o[i] = new
			break
		}
	}
}

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

			return err
		}))

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

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

			return err
		}))

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

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

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

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

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

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

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

	o.copyMatchingRows(o2...)

	return nil
}

type spatialRefSyWhere[Q psql.Filterable] struct {
	Srid      psql.WhereMod[Q, int32]
	AuthName  psql.WhereNullMod[Q, string]
	AuthSrid  psql.WhereNullMod[Q, int32]
	Srtext    psql.WhereNullMod[Q, string]
	Proj4text psql.WhereNullMod[Q, string]
}

func (spatialRefSyWhere[Q]) AliasedAs(alias string) spatialRefSyWhere[Q] {
	return buildSpatialRefSyWhere[Q](buildSpatialRefSyColumns(alias))
}

func buildSpatialRefSyWhere[Q psql.Filterable](cols spatialRefSyColumns) spatialRefSyWhere[Q] {
	return spatialRefSyWhere[Q]{
		Srid:      psql.Where[Q, int32](cols.Srid),
		AuthName:  psql.WhereNull[Q, string](cols.AuthName),
		AuthSrid:  psql.WhereNull[Q, int32](cols.AuthSrid),
		Srtext:    psql.WhereNull[Q, string](cols.Srtext),
		Proj4text: psql.WhereNull[Q, string](cols.Proj4text),
	}
}
