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

// DjangoMigration is an object representing the database table.
type DjangoMigration struct {
	ID      int32     `db:"id,pk,autoincr" `
	App     string    `db:"app" `
	Name    string    `db:"name" `
	Applied time.Time `db:"applied" `
}

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

// DjangoMigrations contains methods to work with the django_migrations table
var DjangoMigrations = mysql.NewTablex[*DjangoMigration, DjangoMigrationSlice, *DjangoMigrationSetter]("django_migrations", buildDjangoMigrationColumns("django_migrations"), []string{"id"})

// DjangoMigrationsQuery is a query on the django_migrations table
type DjangoMigrationsQuery = *mysql.ViewQuery[*DjangoMigration, DjangoMigrationSlice]

func buildDjangoMigrationColumns(alias string) djangoMigrationColumns {
	return djangoMigrationColumns{
		ColumnsExpr: expr.NewColumnsExpr(
			"id", "app", "name", "applied",
		).WithParent("django_migrations"),
		tableAlias: alias,
		ID:         mysql.Quote(alias, "id"),
		App:        mysql.Quote(alias, "app"),
		Name:       mysql.Quote(alias, "name"),
		Applied:    mysql.Quote(alias, "applied"),
	}
}

type djangoMigrationColumns struct {
	expr.ColumnsExpr
	tableAlias string
	ID         mysql.Expression
	App        mysql.Expression
	Name       mysql.Expression
	Applied    mysql.Expression
}

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

func (djangoMigrationColumns) AliasedAs(alias string) djangoMigrationColumns {
	return buildDjangoMigrationColumns(alias)
}

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

func (s DjangoMigrationSetter) SetColumns() []string {
	vals := make([]string, 0, 4)
	if s.ID.IsValue() {
		vals = append(vals, "id")
	}
	if s.App.IsValue() {
		vals = append(vals, "app")
	}
	if s.Name.IsValue() {
		vals = append(vals, "name")
	}
	if s.Applied.IsValue() {
		vals = append(vals, "applied")
	}
	return vals
}

func (s DjangoMigrationSetter) Overwrite(t *DjangoMigration) {
	if s.ID.IsValue() {
		t.ID = s.ID.MustGet()
	}
	if s.App.IsValue() {
		t.App = s.App.MustGet()
	}
	if s.Name.IsValue() {
		t.Name = s.Name.MustGet()
	}
	if s.Applied.IsValue() {
		t.Applied = s.Applied.MustGet()
	}
}

func (s *DjangoMigrationSetter) Apply(q *dialect.InsertQuery) {
	q.AppendHooks(func(ctx context.Context, exec bob.Executor) (context.Context, error) {
		return DjangoMigrations.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.App.IsValue()) {
				return mysql.Raw("DEFAULT").WriteSQL(ctx, w, d, start)
			}
			return mysql.Arg(s.App.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.Applied.IsValue()) {
				return mysql.Raw("DEFAULT").WriteSQL(ctx, w, d, start)
			}
			return mysql.Arg(s.Applied.MustGet()).WriteSQL(ctx, w, d, start)
		}))
}

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

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

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

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

	return exprs
}

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

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

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

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

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

	return err
}

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

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

	s.Overwrite(o)

	return nil
}

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

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

	*o = *o2

	return nil
}

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

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

	return err
}

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

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

			return err
		}))

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

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

			return err
		}))

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

func (o DjangoMigrationSlice) UpdateAll(ctx context.Context, exec bob.Executor, vals DjangoMigrationSetter) error {
	_, err := DjangoMigrations.Update(vals.UpdateMod(), o.UpdateMod()).Exec(ctx, exec)

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

	return err
}

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

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

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

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

	o.copyMatchingRows(o2...)

	return nil
}

type djangoMigrationWhere[Q mysql.Filterable] struct {
	ID      mysql.WhereMod[Q, int32]
	App     mysql.WhereMod[Q, string]
	Name    mysql.WhereMod[Q, string]
	Applied mysql.WhereMod[Q, time.Time]
}

func (djangoMigrationWhere[Q]) AliasedAs(alias string) djangoMigrationWhere[Q] {
	return buildDjangoMigrationWhere[Q](buildDjangoMigrationColumns(alias))
}

func buildDjangoMigrationWhere[Q mysql.Filterable](cols djangoMigrationColumns) djangoMigrationWhere[Q] {
	return djangoMigrationWhere[Q]{
		ID:      mysql.Where[Q, int32](cols.ID),
		App:     mysql.Where[Q, string](cols.App),
		Name:    mysql.Where[Q, string](cols.Name),
		Applied: mysql.Where[Q, time.Time](cols.Applied),
	}
}
