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

// TileService is an object representing the database table.
type TileService struct {
	ID       int32            `db:"id,pk" `
	Name     string           `db:"name" `
	ArcgisID null.Val[string] `db:"arcgis_id" `

	R tileServiceR `db:"-" `
}

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

// TileServices contains methods to work with the service table
var TileServices = psql.NewTablex[*TileService, TileServiceSlice, *TileServiceSetter]("tile", "service", buildTileServiceColumns("tile.service"))

// TileServicesQuery is a query on the service table
type TileServicesQuery = *psql.ViewQuery[*TileService, TileServiceSlice]

// tileServiceR is where relationships are stored.
type tileServiceR struct {
	CachedImages TileCachedImageSlice // tile.cached_image.cached_image_service_id_fkey
}

func buildTileServiceColumns(alias string) tileServiceColumns {
	return tileServiceColumns{
		ColumnsExpr: expr.NewColumnsExpr(
			"id", "name", "arcgis_id",
		).WithParent("tile.service"),
		tableAlias: alias,
		ID:         psql.Quote(alias, "id"),
		Name:       psql.Quote(alias, "name"),
		ArcgisID:   psql.Quote(alias, "arcgis_id"),
	}
}

type tileServiceColumns struct {
	expr.ColumnsExpr
	tableAlias string
	ID         psql.Expression
	Name       psql.Expression
	ArcgisID   psql.Expression
}

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

func (tileServiceColumns) AliasedAs(alias string) tileServiceColumns {
	return buildTileServiceColumns(alias)
}

// TileServiceSetter is used for insert/upsert/update operations
// All values are optional, and do not have to be set
// Generated columns are not included
type TileServiceSetter struct {
	ID       omit.Val[int32]      `db:"id,pk" `
	Name     omit.Val[string]     `db:"name" `
	ArcgisID omitnull.Val[string] `db:"arcgis_id" `
}

func (s TileServiceSetter) SetColumns() []string {
	vals := make([]string, 0, 3)
	if s.ID.IsValue() {
		vals = append(vals, "id")
	}
	if s.Name.IsValue() {
		vals = append(vals, "name")
	}
	if !s.ArcgisID.IsUnset() {
		vals = append(vals, "arcgis_id")
	}
	return vals
}

func (s TileServiceSetter) Overwrite(t *TileService) {
	if s.ID.IsValue() {
		t.ID = s.ID.MustGet()
	}
	if s.Name.IsValue() {
		t.Name = s.Name.MustGet()
	}
	if !s.ArcgisID.IsUnset() {
		t.ArcgisID = s.ArcgisID.MustGetNull()
	}
}

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

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

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

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

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

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

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

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

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

	return exprs
}

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

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

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

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

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

	return err
}

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

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

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

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

	return err
}

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

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

			return err
		}))

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

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

			return err
		}))

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

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

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

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

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

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

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

	o.copyMatchingRows(o2...)

	return nil
}

// CachedImages starts a query for related objects on tile.cached_image
func (o *TileService) CachedImages(mods ...bob.Mod[*dialect.SelectQuery]) TileCachedImagesQuery {
	return TileCachedImages.Query(append(mods,
		sm.Where(TileCachedImages.Columns.ServiceID.EQ(psql.Arg(o.ID))),
	)...)
}

func (os TileServiceSlice) CachedImages(mods ...bob.Mod[*dialect.SelectQuery]) TileCachedImagesQuery {
	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 TileCachedImages.Query(append(mods,
		sm.Where(psql.Group(TileCachedImages.Columns.ServiceID).OP("IN", PKArgExpr)),
	)...)
}

func insertTileServiceCachedImages0(ctx context.Context, exec bob.Executor, tileCachedImages1 []*TileCachedImageSetter, tileService0 *TileService) (TileCachedImageSlice, error) {
	for i := range tileCachedImages1 {
		tileCachedImages1[i].ServiceID = omit.From(tileService0.ID)
	}

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

	return ret, nil
}

func attachTileServiceCachedImages0(ctx context.Context, exec bob.Executor, count int, tileCachedImages1 TileCachedImageSlice, tileService0 *TileService) (TileCachedImageSlice, error) {
	setter := &TileCachedImageSetter{
		ServiceID: omit.From(tileService0.ID),
	}

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

	return tileCachedImages1, nil
}

func (tileService0 *TileService) InsertCachedImages(ctx context.Context, exec bob.Executor, related ...*TileCachedImageSetter) error {
	if len(related) == 0 {
		return nil
	}

	var err error

	tileCachedImages1, err := insertTileServiceCachedImages0(ctx, exec, related, tileService0)
	if err != nil {
		return err
	}

	tileService0.R.CachedImages = append(tileService0.R.CachedImages, tileCachedImages1...)

	for _, rel := range tileCachedImages1 {
		rel.R.Service = tileService0
	}
	return nil
}

func (tileService0 *TileService) AttachCachedImages(ctx context.Context, exec bob.Executor, related ...*TileCachedImage) error {
	if len(related) == 0 {
		return nil
	}

	var err error
	tileCachedImages1 := TileCachedImageSlice(related)

	_, err = attachTileServiceCachedImages0(ctx, exec, len(related), tileCachedImages1, tileService0)
	if err != nil {
		return err
	}

	tileService0.R.CachedImages = append(tileService0.R.CachedImages, tileCachedImages1...)

	for _, rel := range related {
		rel.R.Service = tileService0
	}

	return nil
}

type tileServiceWhere[Q psql.Filterable] struct {
	ID       psql.WhereMod[Q, int32]
	Name     psql.WhereMod[Q, string]
	ArcgisID psql.WhereNullMod[Q, string]
}

func (tileServiceWhere[Q]) AliasedAs(alias string) tileServiceWhere[Q] {
	return buildTileServiceWhere[Q](buildTileServiceColumns(alias))
}

func buildTileServiceWhere[Q psql.Filterable](cols tileServiceColumns) tileServiceWhere[Q] {
	return tileServiceWhere[Q]{
		ID:       psql.Where[Q, int32](cols.ID),
		Name:     psql.Where[Q, string](cols.Name),
		ArcgisID: psql.WhereNull[Q, string](cols.ArcgisID),
	}
}

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

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

		o.R.CachedImages = rels

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

type tileServicePreloader struct{}

func buildTileServicePreloader() tileServicePreloader {
	return tileServicePreloader{}
}

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

func buildTileServiceThenLoader[Q orm.Loadable]() tileServiceThenLoader[Q] {
	type CachedImagesLoadInterface interface {
		LoadCachedImages(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error
	}

	return tileServiceThenLoader[Q]{
		CachedImages: thenLoadBuilder[Q](
			"CachedImages",
			func(ctx context.Context, exec bob.Executor, retrieved CachedImagesLoadInterface, mods ...bob.Mod[*dialect.SelectQuery]) error {
				return retrieved.LoadCachedImages(ctx, exec, mods...)
			},
		),
	}
}

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

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

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

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

	o.R.CachedImages = related
	return nil
}

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

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

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

		o.R.CachedImages = nil
	}

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

		for _, rel := range tileCachedImages {

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

			rel.R.Service = o

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

	return nil
}
