// 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/sm"
	"github.com/Gleipnir-Technology/bob/dialect/psql/um"
	"github.com/Gleipnir-Technology/bob/expr"
	"github.com/Gleipnir-Technology/bob/mods"
	"github.com/Gleipnir-Technology/bob/orm"
	"github.com/Gleipnir-Technology/bob/types/pgtypes"
	"github.com/aarondl/opt/omit"
)

// ComplianceReportRequestMailer is an object representing the database table.
type ComplianceReportRequestMailer struct {
	ComplianceReportRequestID int32 `db:"compliance_report_request_id" `
	MailerID                  int32 `db:"mailer_id" `

	R complianceReportRequestMailerR `db:"-" `
}

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

// ComplianceReportRequestMailers contains methods to work with the compliance_report_request_mailer view
var ComplianceReportRequestMailers = psql.NewViewx[*ComplianceReportRequestMailer, ComplianceReportRequestMailerSlice]("", "compliance_report_request_mailer", buildComplianceReportRequestMailerColumns("compliance_report_request_mailer"))

// ComplianceReportRequestMailersQuery is a query on the compliance_report_request_mailer view
type ComplianceReportRequestMailersQuery = *psql.ViewQuery[*ComplianceReportRequestMailer, ComplianceReportRequestMailerSlice]

// complianceReportRequestMailerR is where relationships are stored.
type complianceReportRequestMailerR struct {
	ComplianceReportRequest *ComplianceReportRequest // compliance_report_request_mailer.compliance_report_request_mai_compliance_report_request_id_fkey
	Mailer                  *CommsMailer             // compliance_report_request_mailer.compliance_report_request_mailer_mailer_id_fkey
}

func buildComplianceReportRequestMailerColumns(alias string) complianceReportRequestMailerColumns {
	return complianceReportRequestMailerColumns{
		ColumnsExpr: expr.NewColumnsExpr(
			"compliance_report_request_id", "mailer_id",
		).WithParent("compliance_report_request_mailer"),
		tableAlias:                alias,
		ComplianceReportRequestID: psql.Quote(alias, "compliance_report_request_id"),
		MailerID:                  psql.Quote(alias, "mailer_id"),
	}
}

type complianceReportRequestMailerColumns struct {
	expr.ColumnsExpr
	tableAlias                string
	ComplianceReportRequestID psql.Expression
	MailerID                  psql.Expression
}

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

func (complianceReportRequestMailerColumns) AliasedAs(alias string) complianceReportRequestMailerColumns {
	return buildComplianceReportRequestMailerColumns(alias)
}

// ComplianceReportRequestMailerSetter is used for insert/upsert/update operations
// All values are optional, and do not have to be set
// Generated columns are not included
type ComplianceReportRequestMailerSetter struct {
	ComplianceReportRequestID omit.Val[int32] `db:"compliance_report_request_id" `
	MailerID                  omit.Val[int32] `db:"mailer_id" `
}

func (s ComplianceReportRequestMailerSetter) SetColumns() []string {
	vals := make([]string, 0, 2)
	if s.ComplianceReportRequestID.IsValue() {
		vals = append(vals, "compliance_report_request_id")
	}
	if s.MailerID.IsValue() {
		vals = append(vals, "mailer_id")
	}
	return vals
}

func (s ComplianceReportRequestMailerSetter) Overwrite(t *ComplianceReportRequestMailer) {
	if s.ComplianceReportRequestID.IsValue() {
		t.ComplianceReportRequestID = s.ComplianceReportRequestID.MustGet()
	}
	if s.MailerID.IsValue() {
		t.MailerID = s.MailerID.MustGet()
	}
}

func (s *ComplianceReportRequestMailerSetter) Apply(q *dialect.InsertQuery) {
	q.AppendValues(bob.ExpressionFunc(func(ctx context.Context, w io.StringWriter, d bob.Dialect, start int) ([]any, error) {
		vals := make([]bob.Expression, 2)
		if s.ComplianceReportRequestID.IsValue() {
			vals[0] = psql.Arg(s.ComplianceReportRequestID.MustGet())
		} else {
			vals[0] = psql.Raw("DEFAULT")
		}

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

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

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

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

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

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

	return exprs
}

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

	switch queryType {
	case bob.QueryTypeSelect:
		ctx, err = ComplianceReportRequestMailers.AfterSelectHooks.RunHooks(ctx, exec, ComplianceReportRequestMailerSlice{o})
	}

	return err
}

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

	switch queryType {
	case bob.QueryTypeSelect:
		ctx, err = ComplianceReportRequestMailers.AfterSelectHooks.RunHooks(ctx, exec, o)
	}

	return err
}

// ComplianceReportRequest starts a query for related objects on compliance_report_request
func (o *ComplianceReportRequestMailer) ComplianceReportRequest(mods ...bob.Mod[*dialect.SelectQuery]) ComplianceReportRequestsQuery {
	return ComplianceReportRequests.Query(append(mods,
		sm.Where(ComplianceReportRequests.Columns.ID.EQ(psql.Arg(o.ComplianceReportRequestID))),
	)...)
}

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

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

// Mailer starts a query for related objects on comms.mailer
func (o *ComplianceReportRequestMailer) Mailer(mods ...bob.Mod[*dialect.SelectQuery]) CommsMailersQuery {
	return CommsMailers.Query(append(mods,
		sm.Where(CommsMailers.Columns.ID.EQ(psql.Arg(o.MailerID))),
	)...)
}

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

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

type complianceReportRequestMailerWhere[Q psql.Filterable] struct {
	ComplianceReportRequestID psql.WhereMod[Q, int32]
	MailerID                  psql.WhereMod[Q, int32]
}

func (complianceReportRequestMailerWhere[Q]) AliasedAs(alias string) complianceReportRequestMailerWhere[Q] {
	return buildComplianceReportRequestMailerWhere[Q](buildComplianceReportRequestMailerColumns(alias))
}

func buildComplianceReportRequestMailerWhere[Q psql.Filterable](cols complianceReportRequestMailerColumns) complianceReportRequestMailerWhere[Q] {
	return complianceReportRequestMailerWhere[Q]{
		ComplianceReportRequestID: psql.Where[Q, int32](cols.ComplianceReportRequestID),
		MailerID:                  psql.Where[Q, int32](cols.MailerID),
	}
}

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

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

		o.R.ComplianceReportRequest = rel

		return nil
	case "Mailer":
		rel, ok := retrieved.(*CommsMailer)
		if !ok {
			return fmt.Errorf("complianceReportRequestMailer cannot load %T as %q", retrieved, name)
		}

		o.R.Mailer = rel

		return nil
	default:
		return fmt.Errorf("complianceReportRequestMailer has no relationship %q", name)
	}
}

type complianceReportRequestMailerPreloader struct {
	ComplianceReportRequest func(...psql.PreloadOption) psql.Preloader
	Mailer                  func(...psql.PreloadOption) psql.Preloader
}

func buildComplianceReportRequestMailerPreloader() complianceReportRequestMailerPreloader {
	return complianceReportRequestMailerPreloader{
		ComplianceReportRequest: func(opts ...psql.PreloadOption) psql.Preloader {
			return psql.Preload[*ComplianceReportRequest, ComplianceReportRequestSlice](psql.PreloadRel{
				Name: "ComplianceReportRequest",
				Sides: []psql.PreloadSide{
					{
						From:        ComplianceReportRequestMailers,
						To:          ComplianceReportRequests,
						FromColumns: []string{"compliance_report_request_id"},
						ToColumns:   []string{"id"},
					},
				},
			}, ComplianceReportRequests.Columns.Names(), opts...)
		},
		Mailer: func(opts ...psql.PreloadOption) psql.Preloader {
			return psql.Preload[*CommsMailer, CommsMailerSlice](psql.PreloadRel{
				Name: "Mailer",
				Sides: []psql.PreloadSide{
					{
						From:        ComplianceReportRequestMailers,
						To:          CommsMailers,
						FromColumns: []string{"mailer_id"},
						ToColumns:   []string{"id"},
					},
				},
			}, CommsMailers.Columns.Names(), opts...)
		},
	}
}

type complianceReportRequestMailerThenLoader[Q orm.Loadable] struct {
	ComplianceReportRequest func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q]
	Mailer                  func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q]
}

func buildComplianceReportRequestMailerThenLoader[Q orm.Loadable]() complianceReportRequestMailerThenLoader[Q] {
	type ComplianceReportRequestLoadInterface interface {
		LoadComplianceReportRequest(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error
	}
	type MailerLoadInterface interface {
		LoadMailer(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error
	}

	return complianceReportRequestMailerThenLoader[Q]{
		ComplianceReportRequest: thenLoadBuilder[Q](
			"ComplianceReportRequest",
			func(ctx context.Context, exec bob.Executor, retrieved ComplianceReportRequestLoadInterface, mods ...bob.Mod[*dialect.SelectQuery]) error {
				return retrieved.LoadComplianceReportRequest(ctx, exec, mods...)
			},
		),
		Mailer: thenLoadBuilder[Q](
			"Mailer",
			func(ctx context.Context, exec bob.Executor, retrieved MailerLoadInterface, mods ...bob.Mod[*dialect.SelectQuery]) error {
				return retrieved.LoadMailer(ctx, exec, mods...)
			},
		),
	}
}

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

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

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

	o.R.ComplianceReportRequest = related
	return nil
}

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

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

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

		for _, rel := range complianceReportRequests {

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

			o.R.ComplianceReportRequest = rel
			break
		}
	}

	return nil
}

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

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

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

	o.R.Mailer = related
	return nil
}

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

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

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

		for _, rel := range commsMailers {

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

			o.R.Mailer = rel
			break
		}
	}

	return nil
}

type complianceReportRequestMailerJoins[Q dialect.Joinable] struct {
	typ                     string
	ComplianceReportRequest modAs[Q, complianceReportRequestColumns]
	Mailer                  modAs[Q, commsMailerColumns]
}

func (j complianceReportRequestMailerJoins[Q]) aliasedAs(alias string) complianceReportRequestMailerJoins[Q] {
	return buildComplianceReportRequestMailerJoins[Q](buildComplianceReportRequestMailerColumns(alias), j.typ)
}

func buildComplianceReportRequestMailerJoins[Q dialect.Joinable](cols complianceReportRequestMailerColumns, typ string) complianceReportRequestMailerJoins[Q] {
	return complianceReportRequestMailerJoins[Q]{
		typ: typ,
		ComplianceReportRequest: modAs[Q, complianceReportRequestColumns]{
			c: ComplianceReportRequests.Columns,
			f: func(to complianceReportRequestColumns) bob.Mod[Q] {
				mods := make(mods.QueryMods[Q], 0, 1)

				{
					mods = append(mods, dialect.Join[Q](typ, ComplianceReportRequests.Name().As(to.Alias())).On(
						to.ID.EQ(cols.ComplianceReportRequestID),
					))
				}

				return mods
			},
		},
		Mailer: modAs[Q, commsMailerColumns]{
			c: CommsMailers.Columns,
			f: func(to commsMailerColumns) bob.Mod[Q] {
				mods := make(mods.QueryMods[Q], 0, 1)

				{
					mods = append(mods, dialect.Join[Q](typ, CommsMailers.Name().As(to.Alias())).On(
						to.ID.EQ(cols.MailerID),
					))
				}

				return mods
			},
		},
	}
}
