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

// AdministrationSetting is an object representing the database table.
type AdministrationSetting struct {
	ID    int32            `db:"id,pk,autoincr" `
	Name  string           `db:"name" `
	Value null.Val[string] `db:"value" `
}

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

// AdministrationSettings contains methods to work with the administration_settings table
var AdministrationSettings = mysql.NewTablex[*AdministrationSetting, AdministrationSettingSlice, *AdministrationSettingSetter]("administration_settings", buildAdministrationSettingColumns("administration_settings"), []string{"id"}, []string{"name"})

// AdministrationSettingsQuery is a query on the administration_settings table
type AdministrationSettingsQuery = *mysql.ViewQuery[*AdministrationSetting, AdministrationSettingSlice]

func buildAdministrationSettingColumns(alias string) administrationSettingColumns {
	return administrationSettingColumns{
		ColumnsExpr: expr.NewColumnsExpr(
			"id", "name", "value",
		).WithParent("administration_settings"),
		tableAlias: alias,
		ID:         mysql.Quote(alias, "id"),
		Name:       mysql.Quote(alias, "name"),
		Value:      mysql.Quote(alias, "value"),
	}
}

type administrationSettingColumns struct {
	expr.ColumnsExpr
	tableAlias string
	ID         mysql.Expression
	Name       mysql.Expression
	Value      mysql.Expression
}

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

func (administrationSettingColumns) AliasedAs(alias string) administrationSettingColumns {
	return buildAdministrationSettingColumns(alias)
}

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

func (s AdministrationSettingSetter) 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.Value.IsUnset() {
		vals = append(vals, "value")
	}
	return vals
}

func (s AdministrationSettingSetter) Overwrite(t *AdministrationSetting) {
	if s.ID.IsValue() {
		t.ID = s.ID.MustGet()
	}
	if s.Name.IsValue() {
		t.Name = s.Name.MustGet()
	}
	if !s.Value.IsUnset() {
		t.Value = s.Value.MustGetNull()
	}
}

func (s *AdministrationSettingSetter) Apply(q *dialect.InsertQuery) {
	q.AppendHooks(func(ctx context.Context, exec bob.Executor) (context.Context, error) {
		return AdministrationSettings.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.Name.IsValue()) {
				return mysql.Raw("DEFAULT").WriteSQL(ctx, w, d, start)
			}
			return mysql.Arg(s.Name.MustGet()).WriteSQL(ctx, w, d, start)
		}), bob.ExpressionFunc(func(ctx context.Context, w io.StringWriter, d bob.Dialect, start int) ([]any, error) {
			if !(!s.Value.IsUnset()) {
				return mysql.Raw("DEFAULT").WriteSQL(ctx, w, d, start)
			}
			return mysql.Arg(s.Value.MustGetNull()).WriteSQL(ctx, w, d, start)
		}))
}

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

func (s AdministrationSettingSetter) 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.Name.IsValue() {
		exprs = append(exprs, expr.Join{Sep: " = ", Exprs: []bob.Expression{
			mysql.Quote(append(prefix, "name")...),
			mysql.Arg(s.Name),
		}})
	}

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

	return exprs
}

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

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

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

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

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

	return err
}

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

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

	s.Overwrite(o)

	return nil
}

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

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

	*o = *o2

	return nil
}

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

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

	return err
}

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

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

			return err
		}))

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

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

			return err
		}))

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

func (o AdministrationSettingSlice) UpdateAll(ctx context.Context, exec bob.Executor, vals AdministrationSettingSetter) error {
	_, err := AdministrationSettings.Update(vals.UpdateMod(), o.UpdateMod()).Exec(ctx, exec)

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

	return err
}

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

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

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

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

	o.copyMatchingRows(o2...)

	return nil
}

type administrationSettingWhere[Q mysql.Filterable] struct {
	ID    mysql.WhereMod[Q, int32]
	Name  mysql.WhereMod[Q, string]
	Value mysql.WhereNullMod[Q, string]
}

func (administrationSettingWhere[Q]) AliasedAs(alias string) administrationSettingWhere[Q] {
	return buildAdministrationSettingWhere[Q](buildAdministrationSettingColumns(alias))
}

func buildAdministrationSettingWhere[Q mysql.Filterable](cols administrationSettingColumns) administrationSettingWhere[Q] {
	return administrationSettingWhere[Q]{
		ID:    mysql.Where[Q, int32](cols.ID),
		Name:  mysql.Where[Q, string](cols.Name),
		Value: mysql.WhereNull[Q, string](cols.Value),
	}
}
