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

	"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/orm"
	"github.com/Gleipnir-Technology/bob/types/pgtypes"
	"github.com/aarondl/opt/null"
	"github.com/aarondl/opt/omit"
	"github.com/aarondl/opt/omitnull"
	enums "source.gleipnir.technology/Gleipnir/nidus-sync/db/enums"
)

// Notification is an object representing the database table.
type Notification struct {
	ID         int32                  `db:"id,pk" `
	Created    time.Time              `db:"created" `
	Link       string                 `db:"link" `
	Message    string                 `db:"message" `
	Type       enums.Notificationtype `db:"type" `
	UserID     int32                  `db:"user_id" `
	ResolvedAt null.Val[time.Time]    `db:"resolved_at" `

	R notificationR `db:"-" `
}

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

// Notifications contains methods to work with the notification table
var Notifications = psql.NewTablex[*Notification, NotificationSlice, *NotificationSetter]("", "notification", buildNotificationColumns("notification"))

// NotificationsQuery is a query on the notification table
type NotificationsQuery = *psql.ViewQuery[*Notification, NotificationSlice]

// notificationR is where relationships are stored.
type notificationR struct {
	UserUser *User // notification.notification_user_id_fkey
}

func buildNotificationColumns(alias string) notificationColumns {
	return notificationColumns{
		ColumnsExpr: expr.NewColumnsExpr(
			"id", "created", "link", "message", "type", "user_id", "resolved_at",
		).WithParent("notification"),
		tableAlias: alias,
		ID:         psql.Quote(alias, "id"),
		Created:    psql.Quote(alias, "created"),
		Link:       psql.Quote(alias, "link"),
		Message:    psql.Quote(alias, "message"),
		Type:       psql.Quote(alias, "type"),
		UserID:     psql.Quote(alias, "user_id"),
		ResolvedAt: psql.Quote(alias, "resolved_at"),
	}
}

type notificationColumns struct {
	expr.ColumnsExpr
	tableAlias string
	ID         psql.Expression
	Created    psql.Expression
	Link       psql.Expression
	Message    psql.Expression
	Type       psql.Expression
	UserID     psql.Expression
	ResolvedAt psql.Expression
}

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

func (notificationColumns) AliasedAs(alias string) notificationColumns {
	return buildNotificationColumns(alias)
}

// NotificationSetter is used for insert/upsert/update operations
// All values are optional, and do not have to be set
// Generated columns are not included
type NotificationSetter struct {
	ID         omit.Val[int32]                  `db:"id,pk" `
	Created    omit.Val[time.Time]              `db:"created" `
	Link       omit.Val[string]                 `db:"link" `
	Message    omit.Val[string]                 `db:"message" `
	Type       omit.Val[enums.Notificationtype] `db:"type" `
	UserID     omit.Val[int32]                  `db:"user_id" `
	ResolvedAt omitnull.Val[time.Time]          `db:"resolved_at" `
}

func (s NotificationSetter) SetColumns() []string {
	vals := make([]string, 0, 7)
	if s.ID.IsValue() {
		vals = append(vals, "id")
	}
	if s.Created.IsValue() {
		vals = append(vals, "created")
	}
	if s.Link.IsValue() {
		vals = append(vals, "link")
	}
	if s.Message.IsValue() {
		vals = append(vals, "message")
	}
	if s.Type.IsValue() {
		vals = append(vals, "type")
	}
	if s.UserID.IsValue() {
		vals = append(vals, "user_id")
	}
	if !s.ResolvedAt.IsUnset() {
		vals = append(vals, "resolved_at")
	}
	return vals
}

func (s NotificationSetter) Overwrite(t *Notification) {
	if s.ID.IsValue() {
		t.ID = s.ID.MustGet()
	}
	if s.Created.IsValue() {
		t.Created = s.Created.MustGet()
	}
	if s.Link.IsValue() {
		t.Link = s.Link.MustGet()
	}
	if s.Message.IsValue() {
		t.Message = s.Message.MustGet()
	}
	if s.Type.IsValue() {
		t.Type = s.Type.MustGet()
	}
	if s.UserID.IsValue() {
		t.UserID = s.UserID.MustGet()
	}
	if !s.ResolvedAt.IsUnset() {
		t.ResolvedAt = s.ResolvedAt.MustGetNull()
	}
}

func (s *NotificationSetter) Apply(q *dialect.InsertQuery) {
	q.AppendHooks(func(ctx context.Context, exec bob.Executor) (context.Context, error) {
		return Notifications.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, 7)
		if s.ID.IsValue() {
			vals[0] = psql.Arg(s.ID.MustGet())
		} else {
			vals[0] = psql.Raw("DEFAULT")
		}

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

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

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

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

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

		if !s.ResolvedAt.IsUnset() {
			vals[6] = psql.Arg(s.ResolvedAt.MustGetNull())
		} else {
			vals[6] = psql.Raw("DEFAULT")
		}

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

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

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

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

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

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

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

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

	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.ResolvedAt.IsUnset() {
		exprs = append(exprs, expr.Join{Sep: " = ", Exprs: []bob.Expression{
			psql.Quote(append(prefix, "resolved_at")...),
			psql.Arg(s.ResolvedAt),
		}})
	}

	return exprs
}

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

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

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

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

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

	return err
}

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

func (o *Notification) pkEQ() dialect.Expression {
	return psql.Quote("notification", "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 Notification
func (o *Notification) Update(ctx context.Context, exec bob.Executor, s *NotificationSetter) error {
	v, err := Notifications.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 Notification record with an executor
func (o *Notification) Delete(ctx context.Context, exec bob.Executor) error {
	_, err := Notifications.Delete(dm.Where(o.pkEQ())).Exec(ctx, exec)
	return err
}

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

	return nil
}

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

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

	return err
}

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

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

			return err
		}))

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

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

			return err
		}))

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

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

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

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

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

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

	o2, err := Notifications.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 user_
func (o *Notification) UserUser(mods ...bob.Mod[*dialect.SelectQuery]) UsersQuery {
	return Users.Query(append(mods,
		sm.Where(Users.Columns.ID.EQ(psql.Arg(o.UserID))),
	)...)
}

func (os NotificationSlice) UserUser(mods ...bob.Mod[*dialect.SelectQuery]) UsersQuery {
	pkUserID := make(pgtypes.Array[int32], 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), "integer[]")),
	))

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

func attachNotificationUserUser0(ctx context.Context, exec bob.Executor, count int, notification0 *Notification, user1 *User) (*Notification, error) {
	setter := &NotificationSetter{
		UserID: omit.From(user1.ID),
	}

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

	return notification0, nil
}

func (notification0 *Notification) InsertUserUser(ctx context.Context, exec bob.Executor, related *UserSetter) error {
	var err error

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

	_, err = attachNotificationUserUser0(ctx, exec, 1, notification0, user1)
	if err != nil {
		return err
	}

	notification0.R.UserUser = user1

	user1.R.UserNotifications = append(user1.R.UserNotifications, notification0)

	return nil
}

func (notification0 *Notification) AttachUserUser(ctx context.Context, exec bob.Executor, user1 *User) error {
	var err error

	_, err = attachNotificationUserUser0(ctx, exec, 1, notification0, user1)
	if err != nil {
		return err
	}

	notification0.R.UserUser = user1

	user1.R.UserNotifications = append(user1.R.UserNotifications, notification0)

	return nil
}

type notificationWhere[Q psql.Filterable] struct {
	ID         psql.WhereMod[Q, int32]
	Created    psql.WhereMod[Q, time.Time]
	Link       psql.WhereMod[Q, string]
	Message    psql.WhereMod[Q, string]
	Type       psql.WhereMod[Q, enums.Notificationtype]
	UserID     psql.WhereMod[Q, int32]
	ResolvedAt psql.WhereNullMod[Q, time.Time]
}

func (notificationWhere[Q]) AliasedAs(alias string) notificationWhere[Q] {
	return buildNotificationWhere[Q](buildNotificationColumns(alias))
}

func buildNotificationWhere[Q psql.Filterable](cols notificationColumns) notificationWhere[Q] {
	return notificationWhere[Q]{
		ID:         psql.Where[Q, int32](cols.ID),
		Created:    psql.Where[Q, time.Time](cols.Created),
		Link:       psql.Where[Q, string](cols.Link),
		Message:    psql.Where[Q, string](cols.Message),
		Type:       psql.Where[Q, enums.Notificationtype](cols.Type),
		UserID:     psql.Where[Q, int32](cols.UserID),
		ResolvedAt: psql.WhereNull[Q, time.Time](cols.ResolvedAt),
	}
}

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

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

		o.R.UserUser = rel

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

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

func buildNotificationPreloader() notificationPreloader {
	return notificationPreloader{
		UserUser: func(opts ...psql.PreloadOption) psql.Preloader {
			return psql.Preload[*User, UserSlice](psql.PreloadRel{
				Name: "UserUser",
				Sides: []psql.PreloadSide{
					{
						From:        Notifications,
						To:          Users,
						FromColumns: []string{"user_id"},
						ToColumns:   []string{"id"},
					},
				},
			}, Users.Columns.Names(), opts...)
		},
	}
}

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

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

	return notificationThenLoader[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 notification's UserUser into the .R struct
func (o *Notification) 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.UserNotifications = NotificationSlice{o}

	o.R.UserUser = related
	return nil
}

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

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

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

		for _, rel := range users {

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

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

			o.R.UserUser = rel
			break
		}
	}

	return nil
}
