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

// StadiaAPIRequest is an object representing the database table.
type StadiaAPIRequest struct {
	ID        int64                       `db:"id,pk" `
	Request   string                      `db:"request" `
	Response  types.JSON[json.RawMessage] `db:"response" `
	CreatedAt time.Time                   `db:"created_at" `
}

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

// StadiaAPIRequests contains methods to work with the api_request table
var StadiaAPIRequests = psql.NewTablex[*StadiaAPIRequest, StadiaAPIRequestSlice, *StadiaAPIRequestSetter]("stadia", "api_request", buildStadiaAPIRequestColumns("stadia.api_request"))

// StadiaAPIRequestsQuery is a query on the api_request table
type StadiaAPIRequestsQuery = *psql.ViewQuery[*StadiaAPIRequest, StadiaAPIRequestSlice]

func buildStadiaAPIRequestColumns(alias string) stadiaAPIRequestColumns {
	return stadiaAPIRequestColumns{
		ColumnsExpr: expr.NewColumnsExpr(
			"id", "request", "response", "created_at",
		).WithParent("stadia.api_request"),
		tableAlias: alias,
		ID:         psql.Quote(alias, "id"),
		Request:    psql.Quote(alias, "request"),
		Response:   psql.Quote(alias, "response"),
		CreatedAt:  psql.Quote(alias, "created_at"),
	}
}

type stadiaAPIRequestColumns struct {
	expr.ColumnsExpr
	tableAlias string
	ID         psql.Expression
	Request    psql.Expression
	Response   psql.Expression
	CreatedAt  psql.Expression
}

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

func (stadiaAPIRequestColumns) AliasedAs(alias string) stadiaAPIRequestColumns {
	return buildStadiaAPIRequestColumns(alias)
}

// StadiaAPIRequestSetter is used for insert/upsert/update operations
// All values are optional, and do not have to be set
// Generated columns are not included
type StadiaAPIRequestSetter struct {
	ID        omit.Val[int64]                       `db:"id,pk" `
	Request   omit.Val[string]                      `db:"request" `
	Response  omit.Val[types.JSON[json.RawMessage]] `db:"response" `
	CreatedAt omit.Val[time.Time]                   `db:"created_at" `
}

func (s StadiaAPIRequestSetter) SetColumns() []string {
	vals := make([]string, 0, 4)
	if s.ID.IsValue() {
		vals = append(vals, "id")
	}
	if s.Request.IsValue() {
		vals = append(vals, "request")
	}
	if s.Response.IsValue() {
		vals = append(vals, "response")
	}
	if s.CreatedAt.IsValue() {
		vals = append(vals, "created_at")
	}
	return vals
}

func (s StadiaAPIRequestSetter) Overwrite(t *StadiaAPIRequest) {
	if s.ID.IsValue() {
		t.ID = s.ID.MustGet()
	}
	if s.Request.IsValue() {
		t.Request = s.Request.MustGet()
	}
	if s.Response.IsValue() {
		t.Response = s.Response.MustGet()
	}
	if s.CreatedAt.IsValue() {
		t.CreatedAt = s.CreatedAt.MustGet()
	}
}

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

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

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

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

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

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

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

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

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

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

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

	return exprs
}

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

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

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

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

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

	return err
}

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

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

	*o = *v

	return nil
}

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

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

	*o = *o2

	return nil
}

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

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

	return err
}

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

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

			return err
		}))

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

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

			return err
		}))

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

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

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

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

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

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

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

	o.copyMatchingRows(o2...)

	return nil
}

type stadiaAPIRequestWhere[Q psql.Filterable] struct {
	ID        psql.WhereMod[Q, int64]
	Request   psql.WhereMod[Q, string]
	Response  psql.WhereMod[Q, types.JSON[json.RawMessage]]
	CreatedAt psql.WhereMod[Q, time.Time]
}

func (stadiaAPIRequestWhere[Q]) AliasedAs(alias string) stadiaAPIRequestWhere[Q] {
	return buildStadiaAPIRequestWhere[Q](buildStadiaAPIRequestColumns(alias))
}

func buildStadiaAPIRequestWhere[Q psql.Filterable](cols stadiaAPIRequestColumns) stadiaAPIRequestWhere[Q] {
	return stadiaAPIRequestWhere[Q]{
		ID:        psql.Where[Q, int64](cols.ID),
		Request:   psql.Where[Q, string](cols.Request),
		Response:  psql.Where[Q, types.JSON[json.RawMessage]](cols.Response),
		CreatedAt: psql.Where[Q, time.Time](cols.CreatedAt),
	}
}
