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

// DjangoSite is an object representing the database table.
type DjangoSite struct {
	ID     int32  `db:"id,pk,autoincr" `
	Domain string `db:"domain" `
	Name   string `db:"name" `
}

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

// DjangoSites contains methods to work with the django_site table
var DjangoSites = mysql.NewTablex[*DjangoSite, DjangoSiteSlice, *DjangoSiteSetter]("django_site", buildDjangoSiteColumns("django_site"), []string{"id"}, []string{"domain"})

// DjangoSitesQuery is a query on the django_site table
type DjangoSitesQuery = *mysql.ViewQuery[*DjangoSite, DjangoSiteSlice]

func buildDjangoSiteColumns(alias string) djangoSiteColumns {
	return djangoSiteColumns{
		ColumnsExpr: expr.NewColumnsExpr(
			"id", "domain", "name",
		).WithParent("django_site"),
		tableAlias: alias,
		ID:         mysql.Quote(alias, "id"),
		Domain:     mysql.Quote(alias, "domain"),
		Name:       mysql.Quote(alias, "name"),
	}
}

type djangoSiteColumns struct {
	expr.ColumnsExpr
	tableAlias string
	ID         mysql.Expression
	Domain     mysql.Expression
	Name       mysql.Expression
}

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

func (djangoSiteColumns) AliasedAs(alias string) djangoSiteColumns {
	return buildDjangoSiteColumns(alias)
}

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

func (s DjangoSiteSetter) SetColumns() []string {
	vals := make([]string, 0, 3)
	if s.ID.IsValue() {
		vals = append(vals, "id")
	}
	if s.Domain.IsValue() {
		vals = append(vals, "domain")
	}
	if s.Name.IsValue() {
		vals = append(vals, "name")
	}
	return vals
}

func (s DjangoSiteSetter) Overwrite(t *DjangoSite) {
	if s.ID.IsValue() {
		t.ID = s.ID.MustGet()
	}
	if s.Domain.IsValue() {
		t.Domain = s.Domain.MustGet()
	}
	if s.Name.IsValue() {
		t.Name = s.Name.MustGet()
	}
}

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

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

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

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

	return exprs
}

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

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

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

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

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

	return err
}

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

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

	s.Overwrite(o)

	return nil
}

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

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

	*o = *o2

	return nil
}

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

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

	return err
}

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

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

			return err
		}))

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

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

			return err
		}))

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

func (o DjangoSiteSlice) UpdateAll(ctx context.Context, exec bob.Executor, vals DjangoSiteSetter) error {
	_, err := DjangoSites.Update(vals.UpdateMod(), o.UpdateMod()).Exec(ctx, exec)

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

	return err
}

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

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

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

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

	o.copyMatchingRows(o2...)

	return nil
}

type djangoSiteWhere[Q mysql.Filterable] struct {
	ID     mysql.WhereMod[Q, int32]
	Domain mysql.WhereMod[Q, string]
	Name   mysql.WhereMod[Q, string]
}

func (djangoSiteWhere[Q]) AliasedAs(alias string) djangoSiteWhere[Q] {
	return buildDjangoSiteWhere[Q](buildDjangoSiteColumns(alias))
}

func buildDjangoSiteWhere[Q mysql.Filterable](cols djangoSiteColumns) djangoSiteWhere[Q] {
	return djangoSiteWhere[Q]{
		ID:     mysql.Where[Q, int32](cols.ID),
		Domain: mysql.Where[Q, string](cols.Domain),
		Name:   mysql.Where[Q, string](cols.Name),
	}
}
