// Code generated by BobGen mysql v0.42.0. 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/aarondl/opt/omit"
	"github.com/stephenafamo/bob"
	"github.com/stephenafamo/bob/dialect/mysql"
	"github.com/stephenafamo/bob/dialect/mysql/dialect"
	"github.com/stephenafamo/bob/dialect/mysql/dm"
	"github.com/stephenafamo/bob/dialect/mysql/sm"
	"github.com/stephenafamo/bob/dialect/mysql/um"
	"github.com/stephenafamo/bob/expr"
	"github.com/stephenafamo/bob/mods"
	"github.com/stephenafamo/bob/orm"
)

// LocationsGPG is an object representing the database table.
type LocationsGPG struct {
	ID      int32  `db:"id,pk,autoincr" `
	SpaceID string `db:"space_id" `
	Key     string `db:"key" `

	R locationsGPGR `db:"-" `
}

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

// LocationsGPGS contains methods to work with the locations_gpg table
var LocationsGPGS = mysql.NewTablex[*LocationsGPG, LocationsGPGSlice, *LocationsGPGSetter]("locations_gpg", buildLocationsGPGColumns("locations_gpg"), []string{"id"}, []string{"space_id"})

// LocationsGPGSQuery is a query on the locations_gpg table
type LocationsGPGSQuery = *mysql.ViewQuery[*LocationsGPG, LocationsGPGSlice]

// locationsGPGR is where relationships are stored.
type locationsGPGR struct {
	SpaceLocationsSpace *LocationsSpace // locations_gpg_space_id_6223440d_fk_locations_space_uuid
}

func buildLocationsGPGColumns(alias string) locationsGPGColumns {
	return locationsGPGColumns{
		ColumnsExpr: expr.NewColumnsExpr(
			"id", "space_id", "key",
		).WithParent("locations_gpg"),
		tableAlias: alias,
		ID:         mysql.Quote(alias, "id"),
		SpaceID:    mysql.Quote(alias, "space_id"),
		Key:        mysql.Quote(alias, "key"),
	}
}

type locationsGPGColumns struct {
	expr.ColumnsExpr
	tableAlias string
	ID         mysql.Expression
	SpaceID    mysql.Expression
	Key        mysql.Expression
}

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

func (locationsGPGColumns) AliasedAs(alias string) locationsGPGColumns {
	return buildLocationsGPGColumns(alias)
}

// LocationsGPGSetter is used for insert/upsert/update operations
// All values are optional, and do not have to be set
// Generated columns are not included
type LocationsGPGSetter struct {
	ID      omit.Val[int32]  `db:"id,pk,autoincr" `
	SpaceID omit.Val[string] `db:"space_id" `
	Key     omit.Val[string] `db:"key" `
}

func (s LocationsGPGSetter) SetColumns() []string {
	vals := make([]string, 0, 3)
	if s.ID.IsValue() {
		vals = append(vals, "id")
	}
	if s.SpaceID.IsValue() {
		vals = append(vals, "space_id")
	}
	if s.Key.IsValue() {
		vals = append(vals, "key")
	}
	return vals
}

func (s LocationsGPGSetter) Overwrite(t *LocationsGPG) {
	if s.ID.IsValue() {
		t.ID = s.ID.MustGet()
	}
	if s.SpaceID.IsValue() {
		t.SpaceID = s.SpaceID.MustGet()
	}
	if s.Key.IsValue() {
		t.Key = s.Key.MustGet()
	}
}

func (s *LocationsGPGSetter) Apply(q *dialect.InsertQuery) {
	q.AppendHooks(func(ctx context.Context, exec bob.Executor) (context.Context, error) {
		return LocationsGPGS.BeforeInsertHooks.RunHooks(ctx, exec, s)
	})

	q.AppendValues(
		bob.ExpressionFunc(func(ctx context.Context, w io.StringWriter, d bob.Dialect, start int) ([]any, error) {
			if !(s.ID.IsValue()) {
				return mysql.Raw("DEFAULT").WriteSQL(ctx, w, d, start)
			}
			return mysql.Arg(s.ID.MustGet()).WriteSQL(ctx, w, d, start)
		}), bob.ExpressionFunc(func(ctx context.Context, w io.StringWriter, d bob.Dialect, start int) ([]any, error) {
			if !(s.SpaceID.IsValue()) {
				return mysql.Raw("DEFAULT").WriteSQL(ctx, w, d, start)
			}
			return mysql.Arg(s.SpaceID.MustGet()).WriteSQL(ctx, w, d, start)
		}), bob.ExpressionFunc(func(ctx context.Context, w io.StringWriter, d bob.Dialect, start int) ([]any, error) {
			if !(s.Key.IsValue()) {
				return mysql.Raw("DEFAULT").WriteSQL(ctx, w, d, start)
			}
			return mysql.Arg(s.Key.MustGet()).WriteSQL(ctx, w, d, start)
		}))
}

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

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

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

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

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

	return exprs
}

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

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

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

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

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

	return err
}

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

func (o *LocationsGPG) pkEQ() dialect.Expression {
	return mysql.Quote("locations_gpg", "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 LocationsGPG
func (o *LocationsGPG) Update(ctx context.Context, exec bob.Executor, s *LocationsGPGSetter) error {
	_, err := LocationsGPGS.Update(s.UpdateMod(), um.Where(o.pkEQ())).Exec(ctx, exec)
	if err != nil {
		return err
	}

	s.Overwrite(o)

	return nil
}

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

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

	return nil
}

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

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

	return err
}

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

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

			return err
		}))

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

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

			return err
		}))

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

func (o LocationsGPGSlice) UpdateAll(ctx context.Context, exec bob.Executor, vals LocationsGPGSetter) error {
	_, err := LocationsGPGS.Update(vals.UpdateMod(), o.UpdateMod()).Exec(ctx, exec)

	for i := range o {
		vals.Overwrite(o[i])
	}

	return err
}

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

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

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

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

	o.copyMatchingRows(o2...)

	return nil
}

// SpaceLocationsSpace starts a query for related objects on locations_space
func (o *LocationsGPG) SpaceLocationsSpace(mods ...bob.Mod[*dialect.SelectQuery]) LocationsSpacesQuery {
	return LocationsSpaces.Query(append(mods,
		sm.Where(LocationsSpaces.Columns.UUID.EQ(mysql.Arg(o.SpaceID))),
	)...)
}

func (os LocationsGPGSlice) SpaceLocationsSpace(mods ...bob.Mod[*dialect.SelectQuery]) LocationsSpacesQuery {
	PKArgSlice := make([]bob.Expression, len(os))
	for i, o := range os {
		PKArgSlice[i] = mysql.ArgGroup(o.SpaceID)
	}
	PKArgExpr := mysql.Group(PKArgSlice...)

	return LocationsSpaces.Query(append(mods,
		sm.Where(mysql.Group(LocationsSpaces.Columns.UUID).OP("IN", PKArgExpr)),
	)...)
}

func attachLocationsGPGSpaceLocationsSpace0(ctx context.Context, exec bob.Executor, count int, locationsGPG0 *LocationsGPG, locationsSpace1 *LocationsSpace) (*LocationsGPG, error) {
	setter := &LocationsGPGSetter{
		SpaceID: omit.From(locationsSpace1.UUID),
	}

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

	return locationsGPG0, nil
}

func (locationsGPG0 *LocationsGPG) InsertSpaceLocationsSpace(ctx context.Context, exec bob.Executor, related *LocationsSpaceSetter) error {
	var err error

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

	_, err = attachLocationsGPGSpaceLocationsSpace0(ctx, exec, 1, locationsGPG0, locationsSpace1)
	if err != nil {
		return err
	}

	locationsGPG0.R.SpaceLocationsSpace = locationsSpace1

	locationsSpace1.R.SpaceLocationsGPG = locationsGPG0

	return nil
}

func (locationsGPG0 *LocationsGPG) AttachSpaceLocationsSpace(ctx context.Context, exec bob.Executor, locationsSpace1 *LocationsSpace) error {
	var err error

	_, err = attachLocationsGPGSpaceLocationsSpace0(ctx, exec, 1, locationsGPG0, locationsSpace1)
	if err != nil {
		return err
	}

	locationsGPG0.R.SpaceLocationsSpace = locationsSpace1

	locationsSpace1.R.SpaceLocationsGPG = locationsGPG0

	return nil
}

type locationsGPGWhere[Q mysql.Filterable] struct {
	ID      mysql.WhereMod[Q, int32]
	SpaceID mysql.WhereMod[Q, string]
	Key     mysql.WhereMod[Q, string]
}

func (locationsGPGWhere[Q]) AliasedAs(alias string) locationsGPGWhere[Q] {
	return buildLocationsGPGWhere[Q](buildLocationsGPGColumns(alias))
}

func buildLocationsGPGWhere[Q mysql.Filterable](cols locationsGPGColumns) locationsGPGWhere[Q] {
	return locationsGPGWhere[Q]{
		ID:      mysql.Where[Q, int32](cols.ID),
		SpaceID: mysql.Where[Q, string](cols.SpaceID),
		Key:     mysql.Where[Q, string](cols.Key),
	}
}

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

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

		o.R.SpaceLocationsSpace = rel

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

type locationsGPGPreloader struct {
	SpaceLocationsSpace func(...mysql.PreloadOption) mysql.Preloader
}

func buildLocationsGPGPreloader() locationsGPGPreloader {
	return locationsGPGPreloader{
		SpaceLocationsSpace: func(opts ...mysql.PreloadOption) mysql.Preloader {
			return mysql.Preload[*LocationsSpace, LocationsSpaceSlice](mysql.PreloadRel{
				Name: "SpaceLocationsSpace",
				Sides: []mysql.PreloadSide{
					{
						From:        LocationsGPGS,
						To:          LocationsSpaces,
						FromColumns: []string{"space_id"},
						ToColumns:   []string{"uuid"},
					},
				},
			}, LocationsSpaces.Columns.Names(), opts...)
		},
	}
}

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

func buildLocationsGPGThenLoader[Q orm.Loadable]() locationsGPGThenLoader[Q] {
	type SpaceLocationsSpaceLoadInterface interface {
		LoadSpaceLocationsSpace(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error
	}

	return locationsGPGThenLoader[Q]{
		SpaceLocationsSpace: thenLoadBuilder[Q](
			"SpaceLocationsSpace",
			func(ctx context.Context, exec bob.Executor, retrieved SpaceLocationsSpaceLoadInterface, mods ...bob.Mod[*dialect.SelectQuery]) error {
				return retrieved.LoadSpaceLocationsSpace(ctx, exec, mods...)
			},
		),
	}
}

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

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

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

	related.R.SpaceLocationsGPG = o

	o.R.SpaceLocationsSpace = related
	return nil
}

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

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

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

		for _, rel := range locationsSpaces {

			if !(o.SpaceID == rel.UUID) {
				continue
			}

			rel.R.SpaceLocationsGPG = o

			o.R.SpaceLocationsSpace = rel
			break
		}
	}

	return nil
}

type locationsGPGJoins[Q dialect.Joinable] struct {
	typ                 string
	SpaceLocationsSpace modAs[Q, locationsSpaceColumns]
}

func (j locationsGPGJoins[Q]) aliasedAs(alias string) locationsGPGJoins[Q] {
	return buildLocationsGPGJoins[Q](buildLocationsGPGColumns(alias), j.typ)
}

func buildLocationsGPGJoins[Q dialect.Joinable](cols locationsGPGColumns, typ string) locationsGPGJoins[Q] {
	return locationsGPGJoins[Q]{
		typ: typ,
		SpaceLocationsSpace: modAs[Q, locationsSpaceColumns]{
			c: LocationsSpaces.Columns,
			f: func(to locationsSpaceColumns) bob.Mod[Q] {
				mods := make(mods.QueryMods[Q], 0, 1)

				{
					mods = append(mods, dialect.Join[Q](typ, LocationsSpaces.Name().As(to.Alias())).On(
						to.UUID.EQ(cols.SpaceID),
					))
				}

				return mods
			},
		},
	}
}
