// 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/orm"
	"github.com/Gleipnir-Technology/bob/types/pgtypes"
	"github.com/aarondl/opt/omit"
)

// FileuploadErrorFile is an object representing the database table.
type FileuploadErrorFile struct {
	FileID  int32  `db:"file_id" `
	ID      int32  `db:"id,pk" `
	Message string `db:"message" `

	R fileuploadErrorFileR `db:"-" `
}

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

// FileuploadErrorFiles contains methods to work with the error_file table
var FileuploadErrorFiles = psql.NewTablex[*FileuploadErrorFile, FileuploadErrorFileSlice, *FileuploadErrorFileSetter]("fileupload", "error_file", buildFileuploadErrorFileColumns("fileupload.error_file"))

// FileuploadErrorFilesQuery is a query on the error_file table
type FileuploadErrorFilesQuery = *psql.ViewQuery[*FileuploadErrorFile, FileuploadErrorFileSlice]

// fileuploadErrorFileR is where relationships are stored.
type fileuploadErrorFileR struct {
	File *FileuploadFile // fileupload.error_file.error_file_file_id_fkey
}

func buildFileuploadErrorFileColumns(alias string) fileuploadErrorFileColumns {
	return fileuploadErrorFileColumns{
		ColumnsExpr: expr.NewColumnsExpr(
			"file_id", "id", "message",
		).WithParent("fileupload.error_file"),
		tableAlias: alias,
		FileID:     psql.Quote(alias, "file_id"),
		ID:         psql.Quote(alias, "id"),
		Message:    psql.Quote(alias, "message"),
	}
}

type fileuploadErrorFileColumns struct {
	expr.ColumnsExpr
	tableAlias string
	FileID     psql.Expression
	ID         psql.Expression
	Message    psql.Expression
}

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

func (fileuploadErrorFileColumns) AliasedAs(alias string) fileuploadErrorFileColumns {
	return buildFileuploadErrorFileColumns(alias)
}

// FileuploadErrorFileSetter is used for insert/upsert/update operations
// All values are optional, and do not have to be set
// Generated columns are not included
type FileuploadErrorFileSetter struct {
	FileID  omit.Val[int32]  `db:"file_id" `
	ID      omit.Val[int32]  `db:"id,pk" `
	Message omit.Val[string] `db:"message" `
}

func (s FileuploadErrorFileSetter) SetColumns() []string {
	vals := make([]string, 0, 3)
	if s.FileID.IsValue() {
		vals = append(vals, "file_id")
	}
	if s.ID.IsValue() {
		vals = append(vals, "id")
	}
	if s.Message.IsValue() {
		vals = append(vals, "message")
	}
	return vals
}

func (s FileuploadErrorFileSetter) Overwrite(t *FileuploadErrorFile) {
	if s.FileID.IsValue() {
		t.FileID = s.FileID.MustGet()
	}
	if s.ID.IsValue() {
		t.ID = s.ID.MustGet()
	}
	if s.Message.IsValue() {
		t.Message = s.Message.MustGet()
	}
}

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

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

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

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

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

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

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

	return exprs
}

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

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

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

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

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

	return err
}

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

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

// Reload refreshes the FileuploadErrorFile using the executor
func (o *FileuploadErrorFile) Reload(ctx context.Context, exec bob.Executor) error {
	o2, err := FileuploadErrorFiles.Query(
		sm.Where(FileuploadErrorFiles.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 FileuploadErrorFileSlice is retrieved from the database
func (o FileuploadErrorFileSlice) AfterQueryHook(ctx context.Context, exec bob.Executor, queryType bob.QueryType) error {
	var err error

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

	return err
}

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

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

			return err
		}))

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

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

			return err
		}))

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

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

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

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

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

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

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

	o.copyMatchingRows(o2...)

	return nil
}

// File starts a query for related objects on fileupload.file
func (o *FileuploadErrorFile) File(mods ...bob.Mod[*dialect.SelectQuery]) FileuploadFilesQuery {
	return FileuploadFiles.Query(append(mods,
		sm.Where(FileuploadFiles.Columns.ID.EQ(psql.Arg(o.FileID))),
	)...)
}

func (os FileuploadErrorFileSlice) File(mods ...bob.Mod[*dialect.SelectQuery]) FileuploadFilesQuery {
	pkFileID := make(pgtypes.Array[int32], 0, len(os))
	for _, o := range os {
		if o == nil {
			continue
		}
		pkFileID = append(pkFileID, o.FileID)
	}
	PKArgExpr := psql.Select(sm.Columns(
		psql.F("unnest", psql.Cast(psql.Arg(pkFileID), "integer[]")),
	))

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

func attachFileuploadErrorFileFile0(ctx context.Context, exec bob.Executor, count int, fileuploadErrorFile0 *FileuploadErrorFile, fileuploadFile1 *FileuploadFile) (*FileuploadErrorFile, error) {
	setter := &FileuploadErrorFileSetter{
		FileID: omit.From(fileuploadFile1.ID),
	}

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

	return fileuploadErrorFile0, nil
}

func (fileuploadErrorFile0 *FileuploadErrorFile) InsertFile(ctx context.Context, exec bob.Executor, related *FileuploadFileSetter) error {
	var err error

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

	_, err = attachFileuploadErrorFileFile0(ctx, exec, 1, fileuploadErrorFile0, fileuploadFile1)
	if err != nil {
		return err
	}

	fileuploadErrorFile0.R.File = fileuploadFile1

	fileuploadFile1.R.ErrorFiles = append(fileuploadFile1.R.ErrorFiles, fileuploadErrorFile0)

	return nil
}

func (fileuploadErrorFile0 *FileuploadErrorFile) AttachFile(ctx context.Context, exec bob.Executor, fileuploadFile1 *FileuploadFile) error {
	var err error

	_, err = attachFileuploadErrorFileFile0(ctx, exec, 1, fileuploadErrorFile0, fileuploadFile1)
	if err != nil {
		return err
	}

	fileuploadErrorFile0.R.File = fileuploadFile1

	fileuploadFile1.R.ErrorFiles = append(fileuploadFile1.R.ErrorFiles, fileuploadErrorFile0)

	return nil
}

type fileuploadErrorFileWhere[Q psql.Filterable] struct {
	FileID  psql.WhereMod[Q, int32]
	ID      psql.WhereMod[Q, int32]
	Message psql.WhereMod[Q, string]
}

func (fileuploadErrorFileWhere[Q]) AliasedAs(alias string) fileuploadErrorFileWhere[Q] {
	return buildFileuploadErrorFileWhere[Q](buildFileuploadErrorFileColumns(alias))
}

func buildFileuploadErrorFileWhere[Q psql.Filterable](cols fileuploadErrorFileColumns) fileuploadErrorFileWhere[Q] {
	return fileuploadErrorFileWhere[Q]{
		FileID:  psql.Where[Q, int32](cols.FileID),
		ID:      psql.Where[Q, int32](cols.ID),
		Message: psql.Where[Q, string](cols.Message),
	}
}

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

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

		o.R.File = rel

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

type fileuploadErrorFilePreloader struct {
	File func(...psql.PreloadOption) psql.Preloader
}

func buildFileuploadErrorFilePreloader() fileuploadErrorFilePreloader {
	return fileuploadErrorFilePreloader{
		File: func(opts ...psql.PreloadOption) psql.Preloader {
			return psql.Preload[*FileuploadFile, FileuploadFileSlice](psql.PreloadRel{
				Name: "File",
				Sides: []psql.PreloadSide{
					{
						From:        FileuploadErrorFiles,
						To:          FileuploadFiles,
						FromColumns: []string{"file_id"},
						ToColumns:   []string{"id"},
					},
				},
			}, FileuploadFiles.Columns.Names(), opts...)
		},
	}
}

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

func buildFileuploadErrorFileThenLoader[Q orm.Loadable]() fileuploadErrorFileThenLoader[Q] {
	type FileLoadInterface interface {
		LoadFile(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error
	}

	return fileuploadErrorFileThenLoader[Q]{
		File: thenLoadBuilder[Q](
			"File",
			func(ctx context.Context, exec bob.Executor, retrieved FileLoadInterface, mods ...bob.Mod[*dialect.SelectQuery]) error {
				return retrieved.LoadFile(ctx, exec, mods...)
			},
		),
	}
}

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

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

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

	related.R.ErrorFiles = FileuploadErrorFileSlice{o}

	o.R.File = related
	return nil
}

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

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

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

		for _, rel := range fileuploadFiles {

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

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

			o.R.File = rel
			break
		}
	}

	return nil
}
