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

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

// TastypieApikey is an object representing the database table.
type TastypieApikey struct {
	ID      int32     `db:"id,pk,autoincr" `
	Key     string    `db:"key" `
	Created time.Time `db:"created" `
	UserID  int32     `db:"user_id" `

	R tastypieApikeyR `db:"-" `
}

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

// TastypieApikeys contains methods to work with the tastypie_apikey table
var TastypieApikeys = mysql.NewTablex[*TastypieApikey, TastypieApikeySlice, *TastypieApikeySetter]("tastypie_apikey", buildTastypieApikeyColumns("tastypie_apikey"), []string{"id"}, []string{"user_id"})

// TastypieApikeysQuery is a query on the tastypie_apikey table
type TastypieApikeysQuery = *mysql.ViewQuery[*TastypieApikey, TastypieApikeySlice]

// tastypieApikeyR is where relationships are stored.
type tastypieApikeyR struct {
	UserAuthUser *AuthUser // tastypie_apikey_user_id_8c8fa920_fk_auth_user_id
}

func buildTastypieApikeyColumns(alias string) tastypieApikeyColumns {
	return tastypieApikeyColumns{
		ColumnsExpr: expr.NewColumnsExpr(
			"id", "key", "created", "user_id",
		).WithParent("tastypie_apikey"),
		tableAlias: alias,
		ID:         mysql.Quote(alias, "id"),
		Key:        mysql.Quote(alias, "key"),
		Created:    mysql.Quote(alias, "created"),
		UserID:     mysql.Quote(alias, "user_id"),
	}
}

type tastypieApikeyColumns struct {
	expr.ColumnsExpr
	tableAlias string
	ID         mysql.Expression
	Key        mysql.Expression
	Created    mysql.Expression
	UserID     mysql.Expression
}

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

func (tastypieApikeyColumns) AliasedAs(alias string) tastypieApikeyColumns {
	return buildTastypieApikeyColumns(alias)
}

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

func (s TastypieApikeySetter) SetColumns() []string {
	vals := make([]string, 0, 4)
	if s.ID.IsValue() {
		vals = append(vals, "id")
	}
	if s.Key.IsValue() {
		vals = append(vals, "key")
	}
	if s.Created.IsValue() {
		vals = append(vals, "created")
	}
	if s.UserID.IsValue() {
		vals = append(vals, "user_id")
	}
	return vals
}

func (s TastypieApikeySetter) Overwrite(t *TastypieApikey) {
	if s.ID.IsValue() {
		t.ID = s.ID.MustGet()
	}
	if s.Key.IsValue() {
		t.Key = s.Key.MustGet()
	}
	if s.Created.IsValue() {
		t.Created = s.Created.MustGet()
	}
	if s.UserID.IsValue() {
		t.UserID = s.UserID.MustGet()
	}
}

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

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

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

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

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

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

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

	return exprs
}

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

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

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

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

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

	return err
}

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

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

	s.Overwrite(o)

	return nil
}

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

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

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

	return err
}

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

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

			return err
		}))

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

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

			return err
		}))

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

func (o TastypieApikeySlice) UpdateAll(ctx context.Context, exec bob.Executor, vals TastypieApikeySetter) error {
	_, err := TastypieApikeys.Update(vals.UpdateMod(), o.UpdateMod()).Exec(ctx, exec)

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

	return err
}

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

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

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

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

	o.copyMatchingRows(o2...)

	return nil
}

// UserAuthUser starts a query for related objects on auth_user
func (o *TastypieApikey) UserAuthUser(mods ...bob.Mod[*dialect.SelectQuery]) AuthUsersQuery {
	return AuthUsers.Query(append(mods,
		sm.Where(AuthUsers.Columns.ID.EQ(mysql.Arg(o.UserID))),
	)...)
}

func (os TastypieApikeySlice) UserAuthUser(mods ...bob.Mod[*dialect.SelectQuery]) AuthUsersQuery {
	PKArgSlice := make([]bob.Expression, len(os))
	for i, o := range os {
		PKArgSlice[i] = mysql.ArgGroup(o.UserID)
	}
	PKArgExpr := mysql.Group(PKArgSlice...)

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

func attachTastypieApikeyUserAuthUser0(ctx context.Context, exec bob.Executor, count int, tastypieApikey0 *TastypieApikey, authUser1 *AuthUser) (*TastypieApikey, error) {
	setter := &TastypieApikeySetter{
		UserID: omit.From(authUser1.ID),
	}

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

	return tastypieApikey0, nil
}

func (tastypieApikey0 *TastypieApikey) InsertUserAuthUser(ctx context.Context, exec bob.Executor, related *AuthUserSetter) error {
	var err error

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

	_, err = attachTastypieApikeyUserAuthUser0(ctx, exec, 1, tastypieApikey0, authUser1)
	if err != nil {
		return err
	}

	tastypieApikey0.R.UserAuthUser = authUser1

	authUser1.R.UserTastypieApikey = tastypieApikey0

	return nil
}

func (tastypieApikey0 *TastypieApikey) AttachUserAuthUser(ctx context.Context, exec bob.Executor, authUser1 *AuthUser) error {
	var err error

	_, err = attachTastypieApikeyUserAuthUser0(ctx, exec, 1, tastypieApikey0, authUser1)
	if err != nil {
		return err
	}

	tastypieApikey0.R.UserAuthUser = authUser1

	authUser1.R.UserTastypieApikey = tastypieApikey0

	return nil
}

type tastypieApikeyWhere[Q mysql.Filterable] struct {
	ID      mysql.WhereMod[Q, int32]
	Key     mysql.WhereMod[Q, string]
	Created mysql.WhereMod[Q, time.Time]
	UserID  mysql.WhereMod[Q, int32]
}

func (tastypieApikeyWhere[Q]) AliasedAs(alias string) tastypieApikeyWhere[Q] {
	return buildTastypieApikeyWhere[Q](buildTastypieApikeyColumns(alias))
}

func buildTastypieApikeyWhere[Q mysql.Filterable](cols tastypieApikeyColumns) tastypieApikeyWhere[Q] {
	return tastypieApikeyWhere[Q]{
		ID:      mysql.Where[Q, int32](cols.ID),
		Key:     mysql.Where[Q, string](cols.Key),
		Created: mysql.Where[Q, time.Time](cols.Created),
		UserID:  mysql.Where[Q, int32](cols.UserID),
	}
}

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

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

		o.R.UserAuthUser = rel

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

type tastypieApikeyPreloader struct {
	UserAuthUser func(...mysql.PreloadOption) mysql.Preloader
}

func buildTastypieApikeyPreloader() tastypieApikeyPreloader {
	return tastypieApikeyPreloader{
		UserAuthUser: func(opts ...mysql.PreloadOption) mysql.Preloader {
			return mysql.Preload[*AuthUser, AuthUserSlice](mysql.PreloadRel{
				Name: "UserAuthUser",
				Sides: []mysql.PreloadSide{
					{
						From:        TastypieApikeys,
						To:          AuthUsers,
						FromColumns: []string{"user_id"},
						ToColumns:   []string{"id"},
					},
				},
			}, AuthUsers.Columns.Names(), opts...)
		},
	}
}

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

func buildTastypieApikeyThenLoader[Q orm.Loadable]() tastypieApikeyThenLoader[Q] {
	type UserAuthUserLoadInterface interface {
		LoadUserAuthUser(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error
	}

	return tastypieApikeyThenLoader[Q]{
		UserAuthUser: thenLoadBuilder[Q](
			"UserAuthUser",
			func(ctx context.Context, exec bob.Executor, retrieved UserAuthUserLoadInterface, mods ...bob.Mod[*dialect.SelectQuery]) error {
				return retrieved.LoadUserAuthUser(ctx, exec, mods...)
			},
		),
	}
}

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

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

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

	related.R.UserTastypieApikey = o

	o.R.UserAuthUser = related
	return nil
}

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

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

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

		for _, rel := range authUsers {

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

			rel.R.UserTastypieApikey = o

			o.R.UserAuthUser = rel
			break
		}
	}

	return nil
}

type tastypieApikeyJoins[Q dialect.Joinable] struct {
	typ          string
	UserAuthUser modAs[Q, authUserColumns]
}

func (j tastypieApikeyJoins[Q]) aliasedAs(alias string) tastypieApikeyJoins[Q] {
	return buildTastypieApikeyJoins[Q](buildTastypieApikeyColumns(alias), j.typ)
}

func buildTastypieApikeyJoins[Q dialect.Joinable](cols tastypieApikeyColumns, typ string) tastypieApikeyJoins[Q] {
	return tastypieApikeyJoins[Q]{
		typ: typ,
		UserAuthUser: modAs[Q, authUserColumns]{
			c: AuthUsers.Columns,
			f: func(to authUserColumns) bob.Mod[Q] {
				mods := make(mods.QueryMods[Q], 0, 1)

				{
					mods = append(mods, dialect.Join[Q](typ, AuthUsers.Name().As(to.Alias())).On(
						to.ID.EQ(cols.UserID),
					))
				}

				return mods
			},
		},
	}
}
