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

// DistrictSubscriptionPhone is an object representing the database table.
type DistrictSubscriptionPhone struct {
	OrganizationID int32  `db:"organization_id,pk" `
	PhoneE164      string `db:"phone_e164,pk" `

	R districtSubscriptionPhoneR `db:"-" `
}

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

// DistrictSubscriptionPhones contains methods to work with the district_subscription_phone table
var DistrictSubscriptionPhones = psql.NewTablex[*DistrictSubscriptionPhone, DistrictSubscriptionPhoneSlice, *DistrictSubscriptionPhoneSetter]("", "district_subscription_phone", buildDistrictSubscriptionPhoneColumns("district_subscription_phone"))

// DistrictSubscriptionPhonesQuery is a query on the district_subscription_phone table
type DistrictSubscriptionPhonesQuery = *psql.ViewQuery[*DistrictSubscriptionPhone, DistrictSubscriptionPhoneSlice]

// districtSubscriptionPhoneR is where relationships are stored.
type districtSubscriptionPhoneR struct {
	Organization   *Organization // district_subscription_phone.district_subscription_phone_organization_id_fkey
	PhoneE164Phone *CommsPhone   // district_subscription_phone.district_subscription_phone_phone_e164_fkey
}

func buildDistrictSubscriptionPhoneColumns(alias string) districtSubscriptionPhoneColumns {
	return districtSubscriptionPhoneColumns{
		ColumnsExpr: expr.NewColumnsExpr(
			"organization_id", "phone_e164",
		).WithParent("district_subscription_phone"),
		tableAlias:     alias,
		OrganizationID: psql.Quote(alias, "organization_id"),
		PhoneE164:      psql.Quote(alias, "phone_e164"),
	}
}

type districtSubscriptionPhoneColumns struct {
	expr.ColumnsExpr
	tableAlias     string
	OrganizationID psql.Expression
	PhoneE164      psql.Expression
}

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

func (districtSubscriptionPhoneColumns) AliasedAs(alias string) districtSubscriptionPhoneColumns {
	return buildDistrictSubscriptionPhoneColumns(alias)
}

// DistrictSubscriptionPhoneSetter is used for insert/upsert/update operations
// All values are optional, and do not have to be set
// Generated columns are not included
type DistrictSubscriptionPhoneSetter struct {
	OrganizationID omit.Val[int32]  `db:"organization_id,pk" `
	PhoneE164      omit.Val[string] `db:"phone_e164,pk" `
}

func (s DistrictSubscriptionPhoneSetter) SetColumns() []string {
	vals := make([]string, 0, 2)
	if s.OrganizationID.IsValue() {
		vals = append(vals, "organization_id")
	}
	if s.PhoneE164.IsValue() {
		vals = append(vals, "phone_e164")
	}
	return vals
}

func (s DistrictSubscriptionPhoneSetter) Overwrite(t *DistrictSubscriptionPhone) {
	if s.OrganizationID.IsValue() {
		t.OrganizationID = s.OrganizationID.MustGet()
	}
	if s.PhoneE164.IsValue() {
		t.PhoneE164 = s.PhoneE164.MustGet()
	}
}

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

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

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

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

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

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

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

	return exprs
}

// FindDistrictSubscriptionPhone retrieves a single record by primary key
// If cols is empty Find will return all columns.
func FindDistrictSubscriptionPhone(ctx context.Context, exec bob.Executor, OrganizationIDPK int32, PhoneE164PK string, cols ...string) (*DistrictSubscriptionPhone, error) {
	if len(cols) == 0 {
		return DistrictSubscriptionPhones.Query(
			sm.Where(DistrictSubscriptionPhones.Columns.OrganizationID.EQ(psql.Arg(OrganizationIDPK))),
			sm.Where(DistrictSubscriptionPhones.Columns.PhoneE164.EQ(psql.Arg(PhoneE164PK))),
		).One(ctx, exec)
	}

	return DistrictSubscriptionPhones.Query(
		sm.Where(DistrictSubscriptionPhones.Columns.OrganizationID.EQ(psql.Arg(OrganizationIDPK))),
		sm.Where(DistrictSubscriptionPhones.Columns.PhoneE164.EQ(psql.Arg(PhoneE164PK))),
		sm.Columns(DistrictSubscriptionPhones.Columns.Only(cols...)),
	).One(ctx, exec)
}

// DistrictSubscriptionPhoneExists checks the presence of a single record by primary key
func DistrictSubscriptionPhoneExists(ctx context.Context, exec bob.Executor, OrganizationIDPK int32, PhoneE164PK string) (bool, error) {
	return DistrictSubscriptionPhones.Query(
		sm.Where(DistrictSubscriptionPhones.Columns.OrganizationID.EQ(psql.Arg(OrganizationIDPK))),
		sm.Where(DistrictSubscriptionPhones.Columns.PhoneE164.EQ(psql.Arg(PhoneE164PK))),
	).Exists(ctx, exec)
}

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

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

	return err
}

// primaryKeyVals returns the primary key values of the DistrictSubscriptionPhone
func (o *DistrictSubscriptionPhone) primaryKeyVals() bob.Expression {
	return psql.ArgGroup(
		o.OrganizationID,
		o.PhoneE164,
	)
}

func (o *DistrictSubscriptionPhone) pkEQ() dialect.Expression {
	return psql.Group(psql.Quote("district_subscription_phone", "organization_id"), psql.Quote("district_subscription_phone", "phone_e164")).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 DistrictSubscriptionPhone
func (o *DistrictSubscriptionPhone) Update(ctx context.Context, exec bob.Executor, s *DistrictSubscriptionPhoneSetter) error {
	v, err := DistrictSubscriptionPhones.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 DistrictSubscriptionPhone record with an executor
func (o *DistrictSubscriptionPhone) Delete(ctx context.Context, exec bob.Executor) error {
	_, err := DistrictSubscriptionPhones.Delete(dm.Where(o.pkEQ())).Exec(ctx, exec)
	return err
}

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

	return nil
}

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

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

	return err
}

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

	return psql.Group(psql.Quote("district_subscription_phone", "organization_id"), psql.Quote("district_subscription_phone", "phone_e164")).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 DistrictSubscriptionPhoneSlice) copyMatchingRows(from ...*DistrictSubscriptionPhone) {
	for i, old := range o {
		for _, new := range from {
			if new.OrganizationID != old.OrganizationID {
				continue
			}
			if new.PhoneE164 != old.PhoneE164 {
				continue
			}
			new.R = old.R
			o[i] = new
			break
		}
	}
}

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

			return err
		}))

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

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

			return err
		}))

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

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

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

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

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

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

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

	o.copyMatchingRows(o2...)

	return nil
}

// Organization starts a query for related objects on organization
func (o *DistrictSubscriptionPhone) Organization(mods ...bob.Mod[*dialect.SelectQuery]) OrganizationsQuery {
	return Organizations.Query(append(mods,
		sm.Where(Organizations.Columns.ID.EQ(psql.Arg(o.OrganizationID))),
	)...)
}

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

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

// PhoneE164Phone starts a query for related objects on comms.phone
func (o *DistrictSubscriptionPhone) PhoneE164Phone(mods ...bob.Mod[*dialect.SelectQuery]) CommsPhonesQuery {
	return CommsPhones.Query(append(mods,
		sm.Where(CommsPhones.Columns.E164.EQ(psql.Arg(o.PhoneE164))),
	)...)
}

func (os DistrictSubscriptionPhoneSlice) PhoneE164Phone(mods ...bob.Mod[*dialect.SelectQuery]) CommsPhonesQuery {
	pkPhoneE164 := make(pgtypes.Array[string], 0, len(os))
	for _, o := range os {
		if o == nil {
			continue
		}
		pkPhoneE164 = append(pkPhoneE164, o.PhoneE164)
	}
	PKArgExpr := psql.Select(sm.Columns(
		psql.F("unnest", psql.Cast(psql.Arg(pkPhoneE164), "text[]")),
	))

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

func attachDistrictSubscriptionPhoneOrganization0(ctx context.Context, exec bob.Executor, count int, districtSubscriptionPhone0 *DistrictSubscriptionPhone, organization1 *Organization) (*DistrictSubscriptionPhone, error) {
	setter := &DistrictSubscriptionPhoneSetter{
		OrganizationID: omit.From(organization1.ID),
	}

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

	return districtSubscriptionPhone0, nil
}

func (districtSubscriptionPhone0 *DistrictSubscriptionPhone) InsertOrganization(ctx context.Context, exec bob.Executor, related *OrganizationSetter) error {
	var err error

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

	_, err = attachDistrictSubscriptionPhoneOrganization0(ctx, exec, 1, districtSubscriptionPhone0, organization1)
	if err != nil {
		return err
	}

	districtSubscriptionPhone0.R.Organization = organization1

	return nil
}

func (districtSubscriptionPhone0 *DistrictSubscriptionPhone) AttachOrganization(ctx context.Context, exec bob.Executor, organization1 *Organization) error {
	var err error

	_, err = attachDistrictSubscriptionPhoneOrganization0(ctx, exec, 1, districtSubscriptionPhone0, organization1)
	if err != nil {
		return err
	}

	districtSubscriptionPhone0.R.Organization = organization1

	return nil
}

func attachDistrictSubscriptionPhonePhoneE164Phone0(ctx context.Context, exec bob.Executor, count int, districtSubscriptionPhone0 *DistrictSubscriptionPhone, commsPhone1 *CommsPhone) (*DistrictSubscriptionPhone, error) {
	setter := &DistrictSubscriptionPhoneSetter{
		PhoneE164: omit.From(commsPhone1.E164),
	}

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

	return districtSubscriptionPhone0, nil
}

func (districtSubscriptionPhone0 *DistrictSubscriptionPhone) InsertPhoneE164Phone(ctx context.Context, exec bob.Executor, related *CommsPhoneSetter) error {
	var err error

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

	_, err = attachDistrictSubscriptionPhonePhoneE164Phone0(ctx, exec, 1, districtSubscriptionPhone0, commsPhone1)
	if err != nil {
		return err
	}

	districtSubscriptionPhone0.R.PhoneE164Phone = commsPhone1

	return nil
}

func (districtSubscriptionPhone0 *DistrictSubscriptionPhone) AttachPhoneE164Phone(ctx context.Context, exec bob.Executor, commsPhone1 *CommsPhone) error {
	var err error

	_, err = attachDistrictSubscriptionPhonePhoneE164Phone0(ctx, exec, 1, districtSubscriptionPhone0, commsPhone1)
	if err != nil {
		return err
	}

	districtSubscriptionPhone0.R.PhoneE164Phone = commsPhone1

	return nil
}

type districtSubscriptionPhoneWhere[Q psql.Filterable] struct {
	OrganizationID psql.WhereMod[Q, int32]
	PhoneE164      psql.WhereMod[Q, string]
}

func (districtSubscriptionPhoneWhere[Q]) AliasedAs(alias string) districtSubscriptionPhoneWhere[Q] {
	return buildDistrictSubscriptionPhoneWhere[Q](buildDistrictSubscriptionPhoneColumns(alias))
}

func buildDistrictSubscriptionPhoneWhere[Q psql.Filterable](cols districtSubscriptionPhoneColumns) districtSubscriptionPhoneWhere[Q] {
	return districtSubscriptionPhoneWhere[Q]{
		OrganizationID: psql.Where[Q, int32](cols.OrganizationID),
		PhoneE164:      psql.Where[Q, string](cols.PhoneE164),
	}
}

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

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

		o.R.Organization = rel

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

		o.R.PhoneE164Phone = rel

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

type districtSubscriptionPhonePreloader struct {
	Organization   func(...psql.PreloadOption) psql.Preloader
	PhoneE164Phone func(...psql.PreloadOption) psql.Preloader
}

func buildDistrictSubscriptionPhonePreloader() districtSubscriptionPhonePreloader {
	return districtSubscriptionPhonePreloader{
		Organization: func(opts ...psql.PreloadOption) psql.Preloader {
			return psql.Preload[*Organization, OrganizationSlice](psql.PreloadRel{
				Name: "Organization",
				Sides: []psql.PreloadSide{
					{
						From:        DistrictSubscriptionPhones,
						To:          Organizations,
						FromColumns: []string{"organization_id"},
						ToColumns:   []string{"id"},
					},
				},
			}, Organizations.Columns.Names(), opts...)
		},
		PhoneE164Phone: func(opts ...psql.PreloadOption) psql.Preloader {
			return psql.Preload[*CommsPhone, CommsPhoneSlice](psql.PreloadRel{
				Name: "PhoneE164Phone",
				Sides: []psql.PreloadSide{
					{
						From:        DistrictSubscriptionPhones,
						To:          CommsPhones,
						FromColumns: []string{"phone_e164"},
						ToColumns:   []string{"e164"},
					},
				},
			}, CommsPhones.Columns.Names(), opts...)
		},
	}
}

type districtSubscriptionPhoneThenLoader[Q orm.Loadable] struct {
	Organization   func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q]
	PhoneE164Phone func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q]
}

func buildDistrictSubscriptionPhoneThenLoader[Q orm.Loadable]() districtSubscriptionPhoneThenLoader[Q] {
	type OrganizationLoadInterface interface {
		LoadOrganization(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error
	}
	type PhoneE164PhoneLoadInterface interface {
		LoadPhoneE164Phone(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error
	}

	return districtSubscriptionPhoneThenLoader[Q]{
		Organization: thenLoadBuilder[Q](
			"Organization",
			func(ctx context.Context, exec bob.Executor, retrieved OrganizationLoadInterface, mods ...bob.Mod[*dialect.SelectQuery]) error {
				return retrieved.LoadOrganization(ctx, exec, mods...)
			},
		),
		PhoneE164Phone: thenLoadBuilder[Q](
			"PhoneE164Phone",
			func(ctx context.Context, exec bob.Executor, retrieved PhoneE164PhoneLoadInterface, mods ...bob.Mod[*dialect.SelectQuery]) error {
				return retrieved.LoadPhoneE164Phone(ctx, exec, mods...)
			},
		),
	}
}

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

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

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

	o.R.Organization = related
	return nil
}

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

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

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

		for _, rel := range organizations {

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

			o.R.Organization = rel
			break
		}
	}

	return nil
}

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

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

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

	o.R.PhoneE164Phone = related
	return nil
}

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

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

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

		for _, rel := range commsPhones {

			if !(o.PhoneE164 == rel.E164) {
				continue
			}

			o.R.PhoneE164Phone = rel
			break
		}
	}

	return nil
}
