// Code generated by BobGen psql v0.42.5. 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"

	"github.com/Gleipnir-Technology/bob"
	"github.com/Gleipnir-Technology/bob/dialect/psql"
	"github.com/Gleipnir-Technology/bob/dialect/psql/dialect"
	"github.com/Gleipnir-Technology/bob/dialect/psql/dm"
	"github.com/Gleipnir-Technology/bob/dialect/psql/sm"
	"github.com/Gleipnir-Technology/bob/dialect/psql/um"
	"github.com/Gleipnir-Technology/bob/expr"
	"github.com/Gleipnir-Technology/bob/mods"
	"github.com/Gleipnir-Technology/bob/orm"
	"github.com/Gleipnir-Technology/bob/types/pgtypes"
	"github.com/aarondl/opt/omit"
)

// ArcgisUserPrivilege is an object representing the database table.
type ArcgisUserPrivilege struct {
	UserID    string `db:"user_id,pk" `
	Privilege string `db:"privilege,pk" `

	R arcgisUserPrivilegeR `db:"-" `
}

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

// ArcgisUserPrivileges contains methods to work with the user_privilege table
var ArcgisUserPrivileges = psql.NewTablex[*ArcgisUserPrivilege, ArcgisUserPrivilegeSlice, *ArcgisUserPrivilegeSetter]("arcgis", "user_privilege", buildArcgisUserPrivilegeColumns("arcgis.user_privilege"))

// ArcgisUserPrivilegesQuery is a query on the user_privilege table
type ArcgisUserPrivilegesQuery = *psql.ViewQuery[*ArcgisUserPrivilege, ArcgisUserPrivilegeSlice]

// arcgisUserPrivilegeR is where relationships are stored.
type arcgisUserPrivilegeR struct {
	UserUser *ArcgisUser // arcgis.user_privilege.user_privilege_user_id_fkey
}

func buildArcgisUserPrivilegeColumns(alias string) arcgisUserPrivilegeColumns {
	return arcgisUserPrivilegeColumns{
		ColumnsExpr: expr.NewColumnsExpr(
			"user_id", "privilege",
		).WithParent("arcgis.user_privilege"),
		tableAlias: alias,
		UserID:     psql.Quote(alias, "user_id"),
		Privilege:  psql.Quote(alias, "privilege"),
	}
}

type arcgisUserPrivilegeColumns struct {
	expr.ColumnsExpr
	tableAlias string
	UserID     psql.Expression
	Privilege  psql.Expression
}

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

func (arcgisUserPrivilegeColumns) AliasedAs(alias string) arcgisUserPrivilegeColumns {
	return buildArcgisUserPrivilegeColumns(alias)
}

// ArcgisUserPrivilegeSetter is used for insert/upsert/update operations
// All values are optional, and do not have to be set
// Generated columns are not included
type ArcgisUserPrivilegeSetter struct {
	UserID    omit.Val[string] `db:"user_id,pk" `
	Privilege omit.Val[string] `db:"privilege,pk" `
}

func (s ArcgisUserPrivilegeSetter) SetColumns() []string {
	vals := make([]string, 0, 2)
	if s.UserID.IsValue() {
		vals = append(vals, "user_id")
	}
	if s.Privilege.IsValue() {
		vals = append(vals, "privilege")
	}
	return vals
}

func (s ArcgisUserPrivilegeSetter) Overwrite(t *ArcgisUserPrivilege) {
	if s.UserID.IsValue() {
		t.UserID = s.UserID.MustGet()
	}
	if s.Privilege.IsValue() {
		t.Privilege = s.Privilege.MustGet()
	}
}

func (s *ArcgisUserPrivilegeSetter) Apply(q *dialect.InsertQuery) {
	q.AppendHooks(func(ctx context.Context, exec bob.Executor) (context.Context, error) {
		return ArcgisUserPrivileges.BeforeInsertHooks.RunHooks(ctx, exec, s)
	})

	q.AppendValues(bob.ExpressionFunc(func(ctx context.Context, w io.StringWriter, d bob.Dialect, start int) ([]any, error) {
		vals := make([]bob.Expression, 2)
		if s.UserID.IsValue() {
			vals[0] = psql.Arg(s.UserID.MustGet())
		} else {
			vals[0] = psql.Raw("DEFAULT")
		}

		if s.Privilege.IsValue() {
			vals[1] = psql.Arg(s.Privilege.MustGet())
		} else {
			vals[1] = psql.Raw("DEFAULT")
		}

		return bob.ExpressSlice(ctx, w, d, start, vals, "", ", ", "")
	}))
}

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

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

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

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

	return exprs
}

// FindArcgisUserPrivilege retrieves a single record by primary key
// If cols is empty Find will return all columns.
func FindArcgisUserPrivilege(ctx context.Context, exec bob.Executor, UserIDPK string, PrivilegePK string, cols ...string) (*ArcgisUserPrivilege, error) {
	if len(cols) == 0 {
		return ArcgisUserPrivileges.Query(
			sm.Where(ArcgisUserPrivileges.Columns.UserID.EQ(psql.Arg(UserIDPK))),
			sm.Where(ArcgisUserPrivileges.Columns.Privilege.EQ(psql.Arg(PrivilegePK))),
		).One(ctx, exec)
	}

	return ArcgisUserPrivileges.Query(
		sm.Where(ArcgisUserPrivileges.Columns.UserID.EQ(psql.Arg(UserIDPK))),
		sm.Where(ArcgisUserPrivileges.Columns.Privilege.EQ(psql.Arg(PrivilegePK))),
		sm.Columns(ArcgisUserPrivileges.Columns.Only(cols...)),
	).One(ctx, exec)
}

// ArcgisUserPrivilegeExists checks the presence of a single record by primary key
func ArcgisUserPrivilegeExists(ctx context.Context, exec bob.Executor, UserIDPK string, PrivilegePK string) (bool, error) {
	return ArcgisUserPrivileges.Query(
		sm.Where(ArcgisUserPrivileges.Columns.UserID.EQ(psql.Arg(UserIDPK))),
		sm.Where(ArcgisUserPrivileges.Columns.Privilege.EQ(psql.Arg(PrivilegePK))),
	).Exists(ctx, exec)
}

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

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

	return err
}

// primaryKeyVals returns the primary key values of the ArcgisUserPrivilege
func (o *ArcgisUserPrivilege) primaryKeyVals() bob.Expression {
	return psql.ArgGroup(
		o.UserID,
		o.Privilege,
	)
}

func (o *ArcgisUserPrivilege) pkEQ() dialect.Expression {
	return psql.Group(psql.Quote("arcgis.user_privilege", "user_id"), psql.Quote("arcgis.user_privilege", "privilege")).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 ArcgisUserPrivilege
func (o *ArcgisUserPrivilege) Update(ctx context.Context, exec bob.Executor, s *ArcgisUserPrivilegeSetter) error {
	v, err := ArcgisUserPrivileges.Update(s.UpdateMod(), um.Where(o.pkEQ())).One(ctx, exec)
	if err != nil {
		return err
	}

	o.R = v.R
	*o = *v

	return nil
}

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

// Reload refreshes the ArcgisUserPrivilege using the executor
func (o *ArcgisUserPrivilege) Reload(ctx context.Context, exec bob.Executor) error {
	o2, err := ArcgisUserPrivileges.Query(
		sm.Where(ArcgisUserPrivileges.Columns.UserID.EQ(psql.Arg(o.UserID))),
		sm.Where(ArcgisUserPrivileges.Columns.Privilege.EQ(psql.Arg(o.Privilege))),
	).One(ctx, exec)
	if err != nil {
		return err
	}
	o2.R = o.R
	*o = *o2

	return nil
}

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

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

	return err
}

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

	return psql.Group(psql.Quote("arcgis.user_privilege", "user_id"), psql.Quote("arcgis.user_privilege", "privilege")).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 ArcgisUserPrivilegeSlice) copyMatchingRows(from ...*ArcgisUserPrivilege) {
	for i, old := range o {
		for _, new := range from {
			if new.UserID != old.UserID {
				continue
			}
			if new.Privilege != old.Privilege {
				continue
			}
			new.R = old.R
			o[i] = new
			break
		}
	}
}

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

			return err
		}))

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

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

			return err
		}))

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

func (o ArcgisUserPrivilegeSlice) UpdateAll(ctx context.Context, exec bob.Executor, vals ArcgisUserPrivilegeSetter) error {
	if len(o) == 0 {
		return nil
	}

	_, err := ArcgisUserPrivileges.Update(vals.UpdateMod(), o.UpdateMod()).All(ctx, exec)
	return err
}

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

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

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

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

	o.copyMatchingRows(o2...)

	return nil
}

// UserUser starts a query for related objects on arcgis.user_
func (o *ArcgisUserPrivilege) UserUser(mods ...bob.Mod[*dialect.SelectQuery]) ArcgisUsersQuery {
	return ArcgisUsers.Query(append(mods,
		sm.Where(ArcgisUsers.Columns.ID.EQ(psql.Arg(o.UserID))),
	)...)
}

func (os ArcgisUserPrivilegeSlice) UserUser(mods ...bob.Mod[*dialect.SelectQuery]) ArcgisUsersQuery {
	pkUserID := make(pgtypes.Array[string], 0, len(os))
	for _, o := range os {
		if o == nil {
			continue
		}
		pkUserID = append(pkUserID, o.UserID)
	}
	PKArgExpr := psql.Select(sm.Columns(
		psql.F("unnest", psql.Cast(psql.Arg(pkUserID), "text[]")),
	))

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

func attachArcgisUserPrivilegeUserUser0(ctx context.Context, exec bob.Executor, count int, arcgisUserPrivilege0 *ArcgisUserPrivilege, arcgisuser1 *ArcgisUser) (*ArcgisUserPrivilege, error) {
	setter := &ArcgisUserPrivilegeSetter{
		UserID: omit.From(arcgisuser1.ID),
	}

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

	return arcgisUserPrivilege0, nil
}

func (arcgisUserPrivilege0 *ArcgisUserPrivilege) InsertUserUser(ctx context.Context, exec bob.Executor, related *ArcgisUserSetter) error {
	var err error

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

	_, err = attachArcgisUserPrivilegeUserUser0(ctx, exec, 1, arcgisUserPrivilege0, arcgisuser1)
	if err != nil {
		return err
	}

	arcgisUserPrivilege0.R.UserUser = arcgisuser1

	arcgisuser1.R.UserUserPrivileges = append(arcgisuser1.R.UserUserPrivileges, arcgisUserPrivilege0)

	return nil
}

func (arcgisUserPrivilege0 *ArcgisUserPrivilege) AttachUserUser(ctx context.Context, exec bob.Executor, arcgisuser1 *ArcgisUser) error {
	var err error

	_, err = attachArcgisUserPrivilegeUserUser0(ctx, exec, 1, arcgisUserPrivilege0, arcgisuser1)
	if err != nil {
		return err
	}

	arcgisUserPrivilege0.R.UserUser = arcgisuser1

	arcgisuser1.R.UserUserPrivileges = append(arcgisuser1.R.UserUserPrivileges, arcgisUserPrivilege0)

	return nil
}

type arcgisUserPrivilegeWhere[Q psql.Filterable] struct {
	UserID    psql.WhereMod[Q, string]
	Privilege psql.WhereMod[Q, string]
}

func (arcgisUserPrivilegeWhere[Q]) AliasedAs(alias string) arcgisUserPrivilegeWhere[Q] {
	return buildArcgisUserPrivilegeWhere[Q](buildArcgisUserPrivilegeColumns(alias))
}

func buildArcgisUserPrivilegeWhere[Q psql.Filterable](cols arcgisUserPrivilegeColumns) arcgisUserPrivilegeWhere[Q] {
	return arcgisUserPrivilegeWhere[Q]{
		UserID:    psql.Where[Q, string](cols.UserID),
		Privilege: psql.Where[Q, string](cols.Privilege),
	}
}

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

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

		o.R.UserUser = rel

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

type arcgisUserPrivilegePreloader struct {
	UserUser func(...psql.PreloadOption) psql.Preloader
}

func buildArcgisUserPrivilegePreloader() arcgisUserPrivilegePreloader {
	return arcgisUserPrivilegePreloader{
		UserUser: func(opts ...psql.PreloadOption) psql.Preloader {
			return psql.Preload[*ArcgisUser, ArcgisUserSlice](psql.PreloadRel{
				Name: "UserUser",
				Sides: []psql.PreloadSide{
					{
						From:        ArcgisUserPrivileges,
						To:          ArcgisUsers,
						FromColumns: []string{"user_id"},
						ToColumns:   []string{"id"},
					},
				},
			}, ArcgisUsers.Columns.Names(), opts...)
		},
	}
}

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

func buildArcgisUserPrivilegeThenLoader[Q orm.Loadable]() arcgisUserPrivilegeThenLoader[Q] {
	type UserUserLoadInterface interface {
		LoadUserUser(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error
	}

	return arcgisUserPrivilegeThenLoader[Q]{
		UserUser: thenLoadBuilder[Q](
			"UserUser",
			func(ctx context.Context, exec bob.Executor, retrieved UserUserLoadInterface, mods ...bob.Mod[*dialect.SelectQuery]) error {
				return retrieved.LoadUserUser(ctx, exec, mods...)
			},
		),
	}
}

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

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

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

	related.R.UserUserPrivileges = ArcgisUserPrivilegeSlice{o}

	o.R.UserUser = related
	return nil
}

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

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

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

		for _, rel := range arcgisusers {

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

			rel.R.UserUserPrivileges = append(rel.R.UserUserPrivileges, o)

			o.R.UserUser = rel
			break
		}
	}

	return nil
}

type arcgisUserPrivilegeJoins[Q dialect.Joinable] struct {
	typ      string
	UserUser modAs[Q, arcgisuserColumns]
}

func (j arcgisUserPrivilegeJoins[Q]) aliasedAs(alias string) arcgisUserPrivilegeJoins[Q] {
	return buildArcgisUserPrivilegeJoins[Q](buildArcgisUserPrivilegeColumns(alias), j.typ)
}

func buildArcgisUserPrivilegeJoins[Q dialect.Joinable](cols arcgisUserPrivilegeColumns, typ string) arcgisUserPrivilegeJoins[Q] {
	return arcgisUserPrivilegeJoins[Q]{
		typ: typ,
		UserUser: modAs[Q, arcgisuserColumns]{
			c: ArcgisUsers.Columns,
			f: func(to arcgisuserColumns) bob.Mod[Q] {
				mods := make(mods.QueryMods[Q], 0, 1)

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

				return mods
			},
		},
	}
}
