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

// TileCachedImage is an object representing the database table.
type TileCachedImage struct {
	X         int32 `db:"x,pk" `
	Y         int32 `db:"y,pk" `
	Z         int32 `db:"z,pk" `
	IsEmpty   bool  `db:"is_empty" `
	ServiceID int32 `db:"service_id,pk" `

	R tileCachedImageR `db:"-" `
}

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

// TileCachedImages contains methods to work with the cached_image table
var TileCachedImages = psql.NewTablex[*TileCachedImage, TileCachedImageSlice, *TileCachedImageSetter]("tile", "cached_image", buildTileCachedImageColumns("tile.cached_image"))

// TileCachedImagesQuery is a query on the cached_image table
type TileCachedImagesQuery = *psql.ViewQuery[*TileCachedImage, TileCachedImageSlice]

// tileCachedImageR is where relationships are stored.
type tileCachedImageR struct {
	Service *TileService // tile.cached_image.cached_image_service_id_fkey
}

func buildTileCachedImageColumns(alias string) tileCachedImageColumns {
	return tileCachedImageColumns{
		ColumnsExpr: expr.NewColumnsExpr(
			"x", "y", "z", "is_empty", "service_id",
		).WithParent("tile.cached_image"),
		tableAlias: alias,
		X:          psql.Quote(alias, "x"),
		Y:          psql.Quote(alias, "y"),
		Z:          psql.Quote(alias, "z"),
		IsEmpty:    psql.Quote(alias, "is_empty"),
		ServiceID:  psql.Quote(alias, "service_id"),
	}
}

type tileCachedImageColumns struct {
	expr.ColumnsExpr
	tableAlias string
	X          psql.Expression
	Y          psql.Expression
	Z          psql.Expression
	IsEmpty    psql.Expression
	ServiceID  psql.Expression
}

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

func (tileCachedImageColumns) AliasedAs(alias string) tileCachedImageColumns {
	return buildTileCachedImageColumns(alias)
}

// TileCachedImageSetter is used for insert/upsert/update operations
// All values are optional, and do not have to be set
// Generated columns are not included
type TileCachedImageSetter struct {
	X         omit.Val[int32] `db:"x,pk" `
	Y         omit.Val[int32] `db:"y,pk" `
	Z         omit.Val[int32] `db:"z,pk" `
	IsEmpty   omit.Val[bool]  `db:"is_empty" `
	ServiceID omit.Val[int32] `db:"service_id,pk" `
}

func (s TileCachedImageSetter) SetColumns() []string {
	vals := make([]string, 0, 5)
	if s.X.IsValue() {
		vals = append(vals, "x")
	}
	if s.Y.IsValue() {
		vals = append(vals, "y")
	}
	if s.Z.IsValue() {
		vals = append(vals, "z")
	}
	if s.IsEmpty.IsValue() {
		vals = append(vals, "is_empty")
	}
	if s.ServiceID.IsValue() {
		vals = append(vals, "service_id")
	}
	return vals
}

func (s TileCachedImageSetter) Overwrite(t *TileCachedImage) {
	if s.X.IsValue() {
		t.X = s.X.MustGet()
	}
	if s.Y.IsValue() {
		t.Y = s.Y.MustGet()
	}
	if s.Z.IsValue() {
		t.Z = s.Z.MustGet()
	}
	if s.IsEmpty.IsValue() {
		t.IsEmpty = s.IsEmpty.MustGet()
	}
	if s.ServiceID.IsValue() {
		t.ServiceID = s.ServiceID.MustGet()
	}
}

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

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

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

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

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

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

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

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

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

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

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

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

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

	return exprs
}

// FindTileCachedImage retrieves a single record by primary key
// If cols is empty Find will return all columns.
func FindTileCachedImage(ctx context.Context, exec bob.Executor, ServiceIDPK int32, XPK int32, YPK int32, ZPK int32, cols ...string) (*TileCachedImage, error) {
	if len(cols) == 0 {
		return TileCachedImages.Query(
			sm.Where(TileCachedImages.Columns.ServiceID.EQ(psql.Arg(ServiceIDPK))),
			sm.Where(TileCachedImages.Columns.X.EQ(psql.Arg(XPK))),
			sm.Where(TileCachedImages.Columns.Y.EQ(psql.Arg(YPK))),
			sm.Where(TileCachedImages.Columns.Z.EQ(psql.Arg(ZPK))),
		).One(ctx, exec)
	}

	return TileCachedImages.Query(
		sm.Where(TileCachedImages.Columns.ServiceID.EQ(psql.Arg(ServiceIDPK))),
		sm.Where(TileCachedImages.Columns.X.EQ(psql.Arg(XPK))),
		sm.Where(TileCachedImages.Columns.Y.EQ(psql.Arg(YPK))),
		sm.Where(TileCachedImages.Columns.Z.EQ(psql.Arg(ZPK))),
		sm.Columns(TileCachedImages.Columns.Only(cols...)),
	).One(ctx, exec)
}

// TileCachedImageExists checks the presence of a single record by primary key
func TileCachedImageExists(ctx context.Context, exec bob.Executor, ServiceIDPK int32, XPK int32, YPK int32, ZPK int32) (bool, error) {
	return TileCachedImages.Query(
		sm.Where(TileCachedImages.Columns.ServiceID.EQ(psql.Arg(ServiceIDPK))),
		sm.Where(TileCachedImages.Columns.X.EQ(psql.Arg(XPK))),
		sm.Where(TileCachedImages.Columns.Y.EQ(psql.Arg(YPK))),
		sm.Where(TileCachedImages.Columns.Z.EQ(psql.Arg(ZPK))),
	).Exists(ctx, exec)
}

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

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

	return err
}

// primaryKeyVals returns the primary key values of the TileCachedImage
func (o *TileCachedImage) primaryKeyVals() bob.Expression {
	return psql.ArgGroup(
		o.ServiceID,
		o.X,
		o.Y,
		o.Z,
	)
}

func (o *TileCachedImage) pkEQ() dialect.Expression {
	return psql.Group(psql.Quote("tile.cached_image", "service_id"), psql.Quote("tile.cached_image", "x"), psql.Quote("tile.cached_image", "y"), psql.Quote("tile.cached_image", "z")).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 TileCachedImage
func (o *TileCachedImage) Update(ctx context.Context, exec bob.Executor, s *TileCachedImageSetter) error {
	v, err := TileCachedImages.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 TileCachedImage record with an executor
func (o *TileCachedImage) Delete(ctx context.Context, exec bob.Executor) error {
	_, err := TileCachedImages.Delete(dm.Where(o.pkEQ())).Exec(ctx, exec)
	return err
}

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

	return nil
}

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

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

	return err
}

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

	return psql.Group(psql.Quote("tile.cached_image", "service_id"), psql.Quote("tile.cached_image", "x"), psql.Quote("tile.cached_image", "y"), psql.Quote("tile.cached_image", "z")).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 TileCachedImageSlice) copyMatchingRows(from ...*TileCachedImage) {
	for i, old := range o {
		for _, new := range from {
			if new.ServiceID != old.ServiceID {
				continue
			}
			if new.X != old.X {
				continue
			}
			if new.Y != old.Y {
				continue
			}
			if new.Z != old.Z {
				continue
			}
			new.R = old.R
			o[i] = new
			break
		}
	}
}

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

			return err
		}))

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

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

			return err
		}))

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

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

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

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

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

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

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

	o.copyMatchingRows(o2...)

	return nil
}

// Service starts a query for related objects on tile.service
func (o *TileCachedImage) Service(mods ...bob.Mod[*dialect.SelectQuery]) TileServicesQuery {
	return TileServices.Query(append(mods,
		sm.Where(TileServices.Columns.ID.EQ(psql.Arg(o.ServiceID))),
	)...)
}

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

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

func attachTileCachedImageService0(ctx context.Context, exec bob.Executor, count int, tileCachedImage0 *TileCachedImage, tileService1 *TileService) (*TileCachedImage, error) {
	setter := &TileCachedImageSetter{
		ServiceID: omit.From(tileService1.ID),
	}

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

	return tileCachedImage0, nil
}

func (tileCachedImage0 *TileCachedImage) InsertService(ctx context.Context, exec bob.Executor, related *TileServiceSetter) error {
	var err error

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

	_, err = attachTileCachedImageService0(ctx, exec, 1, tileCachedImage0, tileService1)
	if err != nil {
		return err
	}

	tileCachedImage0.R.Service = tileService1

	tileService1.R.CachedImages = append(tileService1.R.CachedImages, tileCachedImage0)

	return nil
}

func (tileCachedImage0 *TileCachedImage) AttachService(ctx context.Context, exec bob.Executor, tileService1 *TileService) error {
	var err error

	_, err = attachTileCachedImageService0(ctx, exec, 1, tileCachedImage0, tileService1)
	if err != nil {
		return err
	}

	tileCachedImage0.R.Service = tileService1

	tileService1.R.CachedImages = append(tileService1.R.CachedImages, tileCachedImage0)

	return nil
}

type tileCachedImageWhere[Q psql.Filterable] struct {
	X         psql.WhereMod[Q, int32]
	Y         psql.WhereMod[Q, int32]
	Z         psql.WhereMod[Q, int32]
	IsEmpty   psql.WhereMod[Q, bool]
	ServiceID psql.WhereMod[Q, int32]
}

func (tileCachedImageWhere[Q]) AliasedAs(alias string) tileCachedImageWhere[Q] {
	return buildTileCachedImageWhere[Q](buildTileCachedImageColumns(alias))
}

func buildTileCachedImageWhere[Q psql.Filterable](cols tileCachedImageColumns) tileCachedImageWhere[Q] {
	return tileCachedImageWhere[Q]{
		X:         psql.Where[Q, int32](cols.X),
		Y:         psql.Where[Q, int32](cols.Y),
		Z:         psql.Where[Q, int32](cols.Z),
		IsEmpty:   psql.Where[Q, bool](cols.IsEmpty),
		ServiceID: psql.Where[Q, int32](cols.ServiceID),
	}
}

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

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

		o.R.Service = rel

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

type tileCachedImagePreloader struct {
	Service func(...psql.PreloadOption) psql.Preloader
}

func buildTileCachedImagePreloader() tileCachedImagePreloader {
	return tileCachedImagePreloader{
		Service: func(opts ...psql.PreloadOption) psql.Preloader {
			return psql.Preload[*TileService, TileServiceSlice](psql.PreloadRel{
				Name: "Service",
				Sides: []psql.PreloadSide{
					{
						From:        TileCachedImages,
						To:          TileServices,
						FromColumns: []string{"service_id"},
						ToColumns:   []string{"id"},
					},
				},
			}, TileServices.Columns.Names(), opts...)
		},
	}
}

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

func buildTileCachedImageThenLoader[Q orm.Loadable]() tileCachedImageThenLoader[Q] {
	type ServiceLoadInterface interface {
		LoadService(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error
	}

	return tileCachedImageThenLoader[Q]{
		Service: thenLoadBuilder[Q](
			"Service",
			func(ctx context.Context, exec bob.Executor, retrieved ServiceLoadInterface, mods ...bob.Mod[*dialect.SelectQuery]) error {
				return retrieved.LoadService(ctx, exec, mods...)
			},
		),
	}
}

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

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

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

	related.R.CachedImages = TileCachedImageSlice{o}

	o.R.Service = related
	return nil
}

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

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

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

		for _, rel := range tileServices {

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

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

			o.R.Service = rel
			break
		}
	}

	return nil
}
