// 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"
	"github.com/aarondl/opt/omit"
)

// Session is an object representing the database table.
type Session struct {
	Token  string    `db:"token,pk" `
	Data   []byte    `db:"data" `
	Expiry time.Time `db:"expiry" `
}

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

// Sessions contains methods to work with the sessions table
var Sessions = psql.NewTablex[*Session, SessionSlice, *SessionSetter]("", "sessions", buildSessionColumns("sessions"))

// SessionsQuery is a query on the sessions table
type SessionsQuery = *psql.ViewQuery[*Session, SessionSlice]

func buildSessionColumns(alias string) sessionColumns {
	return sessionColumns{
		ColumnsExpr: expr.NewColumnsExpr(
			"token", "data", "expiry",
		).WithParent("sessions"),
		tableAlias: alias,
		Token:      psql.Quote(alias, "token"),
		Data:       psql.Quote(alias, "data"),
		Expiry:     psql.Quote(alias, "expiry"),
	}
}

type sessionColumns struct {
	expr.ColumnsExpr
	tableAlias string
	Token      psql.Expression
	Data       psql.Expression
	Expiry     psql.Expression
}

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

func (sessionColumns) AliasedAs(alias string) sessionColumns {
	return buildSessionColumns(alias)
}

// SessionSetter is used for insert/upsert/update operations
// All values are optional, and do not have to be set
// Generated columns are not included
type SessionSetter struct {
	Token  omit.Val[string]    `db:"token,pk" `
	Data   omit.Val[[]byte]    `db:"data" `
	Expiry omit.Val[time.Time] `db:"expiry" `
}

func (s SessionSetter) SetColumns() []string {
	vals := make([]string, 0, 3)
	if s.Token.IsValue() {
		vals = append(vals, "token")
	}
	if s.Data.IsValue() {
		vals = append(vals, "data")
	}
	if s.Expiry.IsValue() {
		vals = append(vals, "expiry")
	}
	return vals
}

func (s SessionSetter) Overwrite(t *Session) {
	if s.Token.IsValue() {
		t.Token = s.Token.MustGet()
	}
	if s.Data.IsValue() {
		t.Data = s.Data.MustGet()
	}
	if s.Expiry.IsValue() {
		t.Expiry = s.Expiry.MustGet()
	}
}

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

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

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

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

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

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

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

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

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

	return exprs
}

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

	return Sessions.Query(
		sm.Where(Sessions.Columns.Token.EQ(psql.Arg(TokenPK))),
		sm.Columns(Sessions.Columns.Only(cols...)),
	).One(ctx, exec)
}

// SessionExists checks the presence of a single record by primary key
func SessionExists(ctx context.Context, exec bob.Executor, TokenPK string) (bool, error) {
	return Sessions.Query(
		sm.Where(Sessions.Columns.Token.EQ(psql.Arg(TokenPK))),
	).Exists(ctx, exec)
}

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

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

	return err
}

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

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

	*o = *v

	return nil
}

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

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

	*o = *o2

	return nil
}

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

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

	return err
}

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

	return psql.Quote("sessions", "token").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 SessionSlice) copyMatchingRows(from ...*Session) {
	for i, old := range o {
		for _, new := range from {
			if new.Token != old.Token {
				continue
			}

			o[i] = new
			break
		}
	}
}

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

			return err
		}))

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

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

			return err
		}))

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

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

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

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

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

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

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

	o.copyMatchingRows(o2...)

	return nil
}

type sessionWhere[Q psql.Filterable] struct {
	Token  psql.WhereMod[Q, string]
	Data   psql.WhereMod[Q, []byte]
	Expiry psql.WhereMod[Q, time.Time]
}

func (sessionWhere[Q]) AliasedAs(alias string) sessionWhere[Q] {
	return buildSessionWhere[Q](buildSessionColumns(alias))
}

func buildSessionWhere[Q psql.Filterable](cols sessionColumns) sessionWhere[Q] {
	return sessionWhere[Q]{
		Token:  psql.Where[Q, string](cols.Token),
		Data:   psql.Where[Q, []byte](cols.Data),
		Expiry: psql.Where[Q, time.Time](cols.Expiry),
	}
}
