// 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"
	"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"
	enums "github.com/Gleipnir-Technology/nidus-sync/db/enums"
	"github.com/aarondl/opt/omit"
)

// CommsMailer is an object representing the database table.
type CommsMailer struct {
	Created time.Time             `db:"created" `
	ID      int32                 `db:"id,pk" `
	Type    enums.CommsMailertype `db:"type_" `
}

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

// CommsMailers contains methods to work with the mailer table
var CommsMailers = psql.NewTablex[*CommsMailer, CommsMailerSlice, *CommsMailerSetter]("comms", "mailer", buildCommsMailerColumns("comms.mailer"))

// CommsMailersQuery is a query on the mailer table
type CommsMailersQuery = *psql.ViewQuery[*CommsMailer, CommsMailerSlice]

func buildCommsMailerColumns(alias string) commsMailerColumns {
	return commsMailerColumns{
		ColumnsExpr: expr.NewColumnsExpr(
			"created", "id", "type_",
		).WithParent("comms.mailer"),
		tableAlias: alias,
		Created:    psql.Quote(alias, "created"),
		ID:         psql.Quote(alias, "id"),
		Type:       psql.Quote(alias, "type_"),
	}
}

type commsMailerColumns struct {
	expr.ColumnsExpr
	tableAlias string
	Created    psql.Expression
	ID         psql.Expression
	Type       psql.Expression
}

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

func (commsMailerColumns) AliasedAs(alias string) commsMailerColumns {
	return buildCommsMailerColumns(alias)
}

// CommsMailerSetter is used for insert/upsert/update operations
// All values are optional, and do not have to be set
// Generated columns are not included
type CommsMailerSetter struct {
	Created omit.Val[time.Time]             `db:"created" `
	ID      omit.Val[int32]                 `db:"id,pk" `
	Type    omit.Val[enums.CommsMailertype] `db:"type_" `
}

func (s CommsMailerSetter) SetColumns() []string {
	vals := make([]string, 0, 3)
	if s.Created.IsValue() {
		vals = append(vals, "created")
	}
	if s.ID.IsValue() {
		vals = append(vals, "id")
	}
	if s.Type.IsValue() {
		vals = append(vals, "type_")
	}
	return vals
}

func (s CommsMailerSetter) Overwrite(t *CommsMailer) {
	if s.Created.IsValue() {
		t.Created = s.Created.MustGet()
	}
	if s.ID.IsValue() {
		t.ID = s.ID.MustGet()
	}
	if s.Type.IsValue() {
		t.Type = s.Type.MustGet()
	}
}

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

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

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

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

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

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

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

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

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

	return exprs
}

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

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

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

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

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

	return err
}

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

func (o *CommsMailer) pkEQ() dialect.Expression {
	return psql.Quote("comms.mailer", "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 CommsMailer
func (o *CommsMailer) Update(ctx context.Context, exec bob.Executor, s *CommsMailerSetter) error {
	v, err := CommsMailers.Update(s.UpdateMod(), um.Where(o.pkEQ())).One(ctx, exec)
	if err != nil {
		return err
	}

	*o = *v

	return nil
}

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

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

	*o = *o2

	return nil
}

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

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

	return err
}

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

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

			return err
		}))

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

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

			return err
		}))

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

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

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

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

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

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

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

	o.copyMatchingRows(o2...)

	return nil
}

type commsMailerWhere[Q psql.Filterable] struct {
	Created psql.WhereMod[Q, time.Time]
	ID      psql.WhereMod[Q, int32]
	Type    psql.WhereMod[Q, enums.CommsMailertype]
}

func (commsMailerWhere[Q]) AliasedAs(alias string) commsMailerWhere[Q] {
	return buildCommsMailerWhere[Q](buildCommsMailerColumns(alias))
}

func buildCommsMailerWhere[Q psql.Filterable](cols commsMailerColumns) commsMailerWhere[Q] {
	return commsMailerWhere[Q]{
		Created: psql.Where[Q, time.Time](cols.Created),
		ID:      psql.Where[Q, int32](cols.ID),
		Type:    psql.Where[Q, enums.CommsMailertype](cols.Type),
	}
}
