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

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

// LocationsCallback is an object representing the database table.
type LocationsCallback struct {
	ID             int32            `db:"id,pk,autoincr" `
	UUID           string           `db:"uuid" `
	URI            string           `db:"uri" `
	Event          string           `db:"event" `
	Method         string           `db:"method" `
	ExpectedStatus int32            `db:"expected_status" `
	Enabled        bool             `db:"enabled" `
	Body           null.Val[string] `db:"body" `
	Headers        null.Val[string] `db:"headers" `
}

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

// LocationsCallbacks contains methods to work with the locations_callback table
var LocationsCallbacks = mysql.NewTablex[*LocationsCallback, LocationsCallbackSlice, *LocationsCallbackSetter]("locations_callback", buildLocationsCallbackColumns("locations_callback"), []string{"id"})

// LocationsCallbacksQuery is a query on the locations_callback table
type LocationsCallbacksQuery = *mysql.ViewQuery[*LocationsCallback, LocationsCallbackSlice]

func buildLocationsCallbackColumns(alias string) locationsCallbackColumns {
	return locationsCallbackColumns{
		ColumnsExpr: expr.NewColumnsExpr(
			"id", "uuid", "uri", "event", "method", "expected_status", "enabled", "body", "headers",
		).WithParent("locations_callback"),
		tableAlias:     alias,
		ID:             mysql.Quote(alias, "id"),
		UUID:           mysql.Quote(alias, "uuid"),
		URI:            mysql.Quote(alias, "uri"),
		Event:          mysql.Quote(alias, "event"),
		Method:         mysql.Quote(alias, "method"),
		ExpectedStatus: mysql.Quote(alias, "expected_status"),
		Enabled:        mysql.Quote(alias, "enabled"),
		Body:           mysql.Quote(alias, "body"),
		Headers:        mysql.Quote(alias, "headers"),
	}
}

type locationsCallbackColumns struct {
	expr.ColumnsExpr
	tableAlias     string
	ID             mysql.Expression
	UUID           mysql.Expression
	URI            mysql.Expression
	Event          mysql.Expression
	Method         mysql.Expression
	ExpectedStatus mysql.Expression
	Enabled        mysql.Expression
	Body           mysql.Expression
	Headers        mysql.Expression
}

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

func (locationsCallbackColumns) AliasedAs(alias string) locationsCallbackColumns {
	return buildLocationsCallbackColumns(alias)
}

// LocationsCallbackSetter is used for insert/upsert/update operations
// All values are optional, and do not have to be set
// Generated columns are not included
type LocationsCallbackSetter struct {
	ID             omit.Val[int32]      `db:"id,pk,autoincr" `
	UUID           omit.Val[string]     `db:"uuid" `
	URI            omit.Val[string]     `db:"uri" `
	Event          omit.Val[string]     `db:"event" `
	Method         omit.Val[string]     `db:"method" `
	ExpectedStatus omit.Val[int32]      `db:"expected_status" `
	Enabled        omit.Val[bool]       `db:"enabled" `
	Body           omitnull.Val[string] `db:"body" `
	Headers        omitnull.Val[string] `db:"headers" `
}

func (s LocationsCallbackSetter) SetColumns() []string {
	vals := make([]string, 0, 9)
	if s.ID.IsValue() {
		vals = append(vals, "id")
	}
	if s.UUID.IsValue() {
		vals = append(vals, "uuid")
	}
	if s.URI.IsValue() {
		vals = append(vals, "uri")
	}
	if s.Event.IsValue() {
		vals = append(vals, "event")
	}
	if s.Method.IsValue() {
		vals = append(vals, "method")
	}
	if s.ExpectedStatus.IsValue() {
		vals = append(vals, "expected_status")
	}
	if s.Enabled.IsValue() {
		vals = append(vals, "enabled")
	}
	if !s.Body.IsUnset() {
		vals = append(vals, "body")
	}
	if !s.Headers.IsUnset() {
		vals = append(vals, "headers")
	}
	return vals
}

func (s LocationsCallbackSetter) Overwrite(t *LocationsCallback) {
	if s.ID.IsValue() {
		t.ID = s.ID.MustGet()
	}
	if s.UUID.IsValue() {
		t.UUID = s.UUID.MustGet()
	}
	if s.URI.IsValue() {
		t.URI = s.URI.MustGet()
	}
	if s.Event.IsValue() {
		t.Event = s.Event.MustGet()
	}
	if s.Method.IsValue() {
		t.Method = s.Method.MustGet()
	}
	if s.ExpectedStatus.IsValue() {
		t.ExpectedStatus = s.ExpectedStatus.MustGet()
	}
	if s.Enabled.IsValue() {
		t.Enabled = s.Enabled.MustGet()
	}
	if !s.Body.IsUnset() {
		t.Body = s.Body.MustGetNull()
	}
	if !s.Headers.IsUnset() {
		t.Headers = s.Headers.MustGetNull()
	}
}

func (s *LocationsCallbackSetter) Apply(q *dialect.InsertQuery) {
	q.AppendHooks(func(ctx context.Context, exec bob.Executor) (context.Context, error) {
		return LocationsCallbacks.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.UUID.IsValue()) {
				return mysql.Raw("DEFAULT").WriteSQL(ctx, w, d, start)
			}
			return mysql.Arg(s.UUID.MustGet()).WriteSQL(ctx, w, d, start)
		}), bob.ExpressionFunc(func(ctx context.Context, w io.StringWriter, d bob.Dialect, start int) ([]any, error) {
			if !(s.URI.IsValue()) {
				return mysql.Raw("DEFAULT").WriteSQL(ctx, w, d, start)
			}
			return mysql.Arg(s.URI.MustGet()).WriteSQL(ctx, w, d, start)
		}), bob.ExpressionFunc(func(ctx context.Context, w io.StringWriter, d bob.Dialect, start int) ([]any, error) {
			if !(s.Event.IsValue()) {
				return mysql.Raw("DEFAULT").WriteSQL(ctx, w, d, start)
			}
			return mysql.Arg(s.Event.MustGet()).WriteSQL(ctx, w, d, start)
		}), bob.ExpressionFunc(func(ctx context.Context, w io.StringWriter, d bob.Dialect, start int) ([]any, error) {
			if !(s.Method.IsValue()) {
				return mysql.Raw("DEFAULT").WriteSQL(ctx, w, d, start)
			}
			return mysql.Arg(s.Method.MustGet()).WriteSQL(ctx, w, d, start)
		}), bob.ExpressionFunc(func(ctx context.Context, w io.StringWriter, d bob.Dialect, start int) ([]any, error) {
			if !(s.ExpectedStatus.IsValue()) {
				return mysql.Raw("DEFAULT").WriteSQL(ctx, w, d, start)
			}
			return mysql.Arg(s.ExpectedStatus.MustGet()).WriteSQL(ctx, w, d, start)
		}), bob.ExpressionFunc(func(ctx context.Context, w io.StringWriter, d bob.Dialect, start int) ([]any, error) {
			if !(s.Enabled.IsValue()) {
				return mysql.Raw("DEFAULT").WriteSQL(ctx, w, d, start)
			}
			return mysql.Arg(s.Enabled.MustGet()).WriteSQL(ctx, w, d, start)
		}), bob.ExpressionFunc(func(ctx context.Context, w io.StringWriter, d bob.Dialect, start int) ([]any, error) {
			if !(!s.Body.IsUnset()) {
				return mysql.Raw("DEFAULT").WriteSQL(ctx, w, d, start)
			}
			return mysql.Arg(s.Body.MustGetNull()).WriteSQL(ctx, w, d, start)
		}), bob.ExpressionFunc(func(ctx context.Context, w io.StringWriter, d bob.Dialect, start int) ([]any, error) {
			if !(!s.Headers.IsUnset()) {
				return mysql.Raw("DEFAULT").WriteSQL(ctx, w, d, start)
			}
			return mysql.Arg(s.Headers.MustGetNull()).WriteSQL(ctx, w, d, start)
		}))
}

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

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

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

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

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

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

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

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

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

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

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

	return exprs
}

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

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

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

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

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

	return err
}

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

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

	s.Overwrite(o)

	return nil
}

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

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

	*o = *o2

	return nil
}

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

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

	return err
}

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

	return mysql.Quote("locations_callback", "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 LocationsCallbackSlice) copyMatchingRows(from ...*LocationsCallback) {
	for i, old := range o {
		for _, new := range from {
			if new.ID != old.ID {
				continue
			}

			o[i] = new
			break
		}
	}
}

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

			return err
		}))

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

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

			return err
		}))

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

func (o LocationsCallbackSlice) UpdateAll(ctx context.Context, exec bob.Executor, vals LocationsCallbackSetter) error {
	_, err := LocationsCallbacks.Update(vals.UpdateMod(), o.UpdateMod()).Exec(ctx, exec)

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

	return err
}

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

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

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

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

	o.copyMatchingRows(o2...)

	return nil
}

type locationsCallbackWhere[Q mysql.Filterable] struct {
	ID             mysql.WhereMod[Q, int32]
	UUID           mysql.WhereMod[Q, string]
	URI            mysql.WhereMod[Q, string]
	Event          mysql.WhereMod[Q, string]
	Method         mysql.WhereMod[Q, string]
	ExpectedStatus mysql.WhereMod[Q, int32]
	Enabled        mysql.WhereMod[Q, bool]
	Body           mysql.WhereNullMod[Q, string]
	Headers        mysql.WhereNullMod[Q, string]
}

func (locationsCallbackWhere[Q]) AliasedAs(alias string) locationsCallbackWhere[Q] {
	return buildLocationsCallbackWhere[Q](buildLocationsCallbackColumns(alias))
}

func buildLocationsCallbackWhere[Q mysql.Filterable](cols locationsCallbackColumns) locationsCallbackWhere[Q] {
	return locationsCallbackWhere[Q]{
		ID:             mysql.Where[Q, int32](cols.ID),
		UUID:           mysql.Where[Q, string](cols.UUID),
		URI:            mysql.Where[Q, string](cols.URI),
		Event:          mysql.Where[Q, string](cols.Event),
		Method:         mysql.Where[Q, string](cols.Method),
		ExpectedStatus: mysql.Where[Q, int32](cols.ExpectedStatus),
		Enabled:        mysql.Where[Q, bool](cols.Enabled),
		Body:           mysql.WhereNull[Q, string](cols.Body),
		Headers:        mysql.WhereNull[Q, string](cols.Headers),
	}
}
