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

// PublicreportImageExif is an object representing the database table.
type PublicreportImageExif struct {
	ImageID int32  `db:"image_id,pk" `
	Name    string `db:"name,pk" `
	Value   string `db:"value,pk" `

	R publicreportImageExifR `db:"-" `
}

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

// PublicreportImageExifs contains methods to work with the image_exif table
var PublicreportImageExifs = psql.NewTablex[*PublicreportImageExif, PublicreportImageExifSlice, *PublicreportImageExifSetter]("publicreport", "image_exif", buildPublicreportImageExifColumns("publicreport.image_exif"))

// PublicreportImageExifsQuery is a query on the image_exif table
type PublicreportImageExifsQuery = *psql.ViewQuery[*PublicreportImageExif, PublicreportImageExifSlice]

// publicreportImageExifR is where relationships are stored.
type publicreportImageExifR struct {
	Image *PublicreportImage // publicreport.image_exif.image_exif_image_id_fkey
}

func buildPublicreportImageExifColumns(alias string) publicreportImageExifColumns {
	return publicreportImageExifColumns{
		ColumnsExpr: expr.NewColumnsExpr(
			"image_id", "name", "value",
		).WithParent("publicreport.image_exif"),
		tableAlias: alias,
		ImageID:    psql.Quote(alias, "image_id"),
		Name:       psql.Quote(alias, "name"),
		Value:      psql.Quote(alias, "value"),
	}
}

type publicreportImageExifColumns struct {
	expr.ColumnsExpr
	tableAlias string
	ImageID    psql.Expression
	Name       psql.Expression
	Value      psql.Expression
}

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

func (publicreportImageExifColumns) AliasedAs(alias string) publicreportImageExifColumns {
	return buildPublicreportImageExifColumns(alias)
}

// PublicreportImageExifSetter is used for insert/upsert/update operations
// All values are optional, and do not have to be set
// Generated columns are not included
type PublicreportImageExifSetter struct {
	ImageID omit.Val[int32]  `db:"image_id,pk" `
	Name    omit.Val[string] `db:"name,pk" `
	Value   omit.Val[string] `db:"value,pk" `
}

func (s PublicreportImageExifSetter) SetColumns() []string {
	vals := make([]string, 0, 3)
	if s.ImageID.IsValue() {
		vals = append(vals, "image_id")
	}
	if s.Name.IsValue() {
		vals = append(vals, "name")
	}
	if s.Value.IsValue() {
		vals = append(vals, "value")
	}
	return vals
}

func (s PublicreportImageExifSetter) Overwrite(t *PublicreportImageExif) {
	if s.ImageID.IsValue() {
		t.ImageID = s.ImageID.MustGet()
	}
	if s.Name.IsValue() {
		t.Name = s.Name.MustGet()
	}
	if s.Value.IsValue() {
		t.Value = s.Value.MustGet()
	}
}

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

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

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

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

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

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

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

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

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

	return exprs
}

// FindPublicreportImageExif retrieves a single record by primary key
// If cols is empty Find will return all columns.
func FindPublicreportImageExif(ctx context.Context, exec bob.Executor, ImageIDPK int32, NamePK string, ValuePK string, cols ...string) (*PublicreportImageExif, error) {
	if len(cols) == 0 {
		return PublicreportImageExifs.Query(
			sm.Where(PublicreportImageExifs.Columns.ImageID.EQ(psql.Arg(ImageIDPK))),
			sm.Where(PublicreportImageExifs.Columns.Name.EQ(psql.Arg(NamePK))),
			sm.Where(PublicreportImageExifs.Columns.Value.EQ(psql.Arg(ValuePK))),
		).One(ctx, exec)
	}

	return PublicreportImageExifs.Query(
		sm.Where(PublicreportImageExifs.Columns.ImageID.EQ(psql.Arg(ImageIDPK))),
		sm.Where(PublicreportImageExifs.Columns.Name.EQ(psql.Arg(NamePK))),
		sm.Where(PublicreportImageExifs.Columns.Value.EQ(psql.Arg(ValuePK))),
		sm.Columns(PublicreportImageExifs.Columns.Only(cols...)),
	).One(ctx, exec)
}

// PublicreportImageExifExists checks the presence of a single record by primary key
func PublicreportImageExifExists(ctx context.Context, exec bob.Executor, ImageIDPK int32, NamePK string, ValuePK string) (bool, error) {
	return PublicreportImageExifs.Query(
		sm.Where(PublicreportImageExifs.Columns.ImageID.EQ(psql.Arg(ImageIDPK))),
		sm.Where(PublicreportImageExifs.Columns.Name.EQ(psql.Arg(NamePK))),
		sm.Where(PublicreportImageExifs.Columns.Value.EQ(psql.Arg(ValuePK))),
	).Exists(ctx, exec)
}

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

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

	return err
}

// primaryKeyVals returns the primary key values of the PublicreportImageExif
func (o *PublicreportImageExif) primaryKeyVals() bob.Expression {
	return psql.ArgGroup(
		o.ImageID,
		o.Name,
		o.Value,
	)
}

func (o *PublicreportImageExif) pkEQ() dialect.Expression {
	return psql.Group(psql.Quote("publicreport.image_exif", "image_id"), psql.Quote("publicreport.image_exif", "name"), psql.Quote("publicreport.image_exif", "value")).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 PublicreportImageExif
func (o *PublicreportImageExif) Update(ctx context.Context, exec bob.Executor, s *PublicreportImageExifSetter) error {
	v, err := PublicreportImageExifs.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 PublicreportImageExif record with an executor
func (o *PublicreportImageExif) Delete(ctx context.Context, exec bob.Executor) error {
	_, err := PublicreportImageExifs.Delete(dm.Where(o.pkEQ())).Exec(ctx, exec)
	return err
}

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

	return nil
}

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

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

	return err
}

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

	return psql.Group(psql.Quote("publicreport.image_exif", "image_id"), psql.Quote("publicreport.image_exif", "name"), psql.Quote("publicreport.image_exif", "value")).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 PublicreportImageExifSlice) copyMatchingRows(from ...*PublicreportImageExif) {
	for i, old := range o {
		for _, new := range from {
			if new.ImageID != old.ImageID {
				continue
			}
			if new.Name != old.Name {
				continue
			}
			if new.Value != old.Value {
				continue
			}
			new.R = old.R
			o[i] = new
			break
		}
	}
}

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

			return err
		}))

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

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

			return err
		}))

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

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

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

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

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

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

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

	o.copyMatchingRows(o2...)

	return nil
}

// Image starts a query for related objects on publicreport.image
func (o *PublicreportImageExif) Image(mods ...bob.Mod[*dialect.SelectQuery]) PublicreportImagesQuery {
	return PublicreportImages.Query(append(mods,
		sm.Where(PublicreportImages.Columns.ID.EQ(psql.Arg(o.ImageID))),
	)...)
}

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

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

func attachPublicreportImageExifImage0(ctx context.Context, exec bob.Executor, count int, publicreportImageExif0 *PublicreportImageExif, publicreportImage1 *PublicreportImage) (*PublicreportImageExif, error) {
	setter := &PublicreportImageExifSetter{
		ImageID: omit.From(publicreportImage1.ID),
	}

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

	return publicreportImageExif0, nil
}

func (publicreportImageExif0 *PublicreportImageExif) InsertImage(ctx context.Context, exec bob.Executor, related *PublicreportImageSetter) error {
	var err error

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

	_, err = attachPublicreportImageExifImage0(ctx, exec, 1, publicreportImageExif0, publicreportImage1)
	if err != nil {
		return err
	}

	publicreportImageExif0.R.Image = publicreportImage1

	publicreportImage1.R.ImageExifs = append(publicreportImage1.R.ImageExifs, publicreportImageExif0)

	return nil
}

func (publicreportImageExif0 *PublicreportImageExif) AttachImage(ctx context.Context, exec bob.Executor, publicreportImage1 *PublicreportImage) error {
	var err error

	_, err = attachPublicreportImageExifImage0(ctx, exec, 1, publicreportImageExif0, publicreportImage1)
	if err != nil {
		return err
	}

	publicreportImageExif0.R.Image = publicreportImage1

	publicreportImage1.R.ImageExifs = append(publicreportImage1.R.ImageExifs, publicreportImageExif0)

	return nil
}

type publicreportImageExifWhere[Q psql.Filterable] struct {
	ImageID psql.WhereMod[Q, int32]
	Name    psql.WhereMod[Q, string]
	Value   psql.WhereMod[Q, string]
}

func (publicreportImageExifWhere[Q]) AliasedAs(alias string) publicreportImageExifWhere[Q] {
	return buildPublicreportImageExifWhere[Q](buildPublicreportImageExifColumns(alias))
}

func buildPublicreportImageExifWhere[Q psql.Filterable](cols publicreportImageExifColumns) publicreportImageExifWhere[Q] {
	return publicreportImageExifWhere[Q]{
		ImageID: psql.Where[Q, int32](cols.ImageID),
		Name:    psql.Where[Q, string](cols.Name),
		Value:   psql.Where[Q, string](cols.Value),
	}
}

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

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

		o.R.Image = rel

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

type publicreportImageExifPreloader struct {
	Image func(...psql.PreloadOption) psql.Preloader
}

func buildPublicreportImageExifPreloader() publicreportImageExifPreloader {
	return publicreportImageExifPreloader{
		Image: func(opts ...psql.PreloadOption) psql.Preloader {
			return psql.Preload[*PublicreportImage, PublicreportImageSlice](psql.PreloadRel{
				Name: "Image",
				Sides: []psql.PreloadSide{
					{
						From:        PublicreportImageExifs,
						To:          PublicreportImages,
						FromColumns: []string{"image_id"},
						ToColumns:   []string{"id"},
					},
				},
			}, PublicreportImages.Columns.Names(), opts...)
		},
	}
}

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

func buildPublicreportImageExifThenLoader[Q orm.Loadable]() publicreportImageExifThenLoader[Q] {
	type ImageLoadInterface interface {
		LoadImage(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error
	}

	return publicreportImageExifThenLoader[Q]{
		Image: thenLoadBuilder[Q](
			"Image",
			func(ctx context.Context, exec bob.Executor, retrieved ImageLoadInterface, mods ...bob.Mod[*dialect.SelectQuery]) error {
				return retrieved.LoadImage(ctx, exec, mods...)
			},
		),
	}
}

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

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

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

	related.R.ImageExifs = PublicreportImageExifSlice{o}

	o.R.Image = related
	return nil
}

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

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

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

		for _, rel := range publicreportImages {

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

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

			o.R.Image = rel
			break
		}
	}

	return nil
}
