package comms

import (
	"context"
	"fmt"

	//"github.com/Gleipnir-Technology/bob"
	"source.gleipnir.technology/Gleipnir/nidus-sync/db"
	//"source.gleipnir.technology/Gleipnir/nidus-sync/db/gen/nidus-sync/public/enum"
	"github.com/Gleipnir-Technology/jet/postgres"
	"source.gleipnir.technology/Gleipnir/nidus-sync/db/gen/nidus-sync/comms/model"
	"source.gleipnir.technology/Gleipnir/nidus-sync/db/gen/nidus-sync/comms/table"
)

func ContactEmailInsert(ctx context.Context, txn db.Ex, m model.ContactEmail) (model.ContactEmail, error) {
	statement := table.ContactEmail.INSERT(table.ContactEmail.AllColumns).
		MODEL(m).
		RETURNING(table.ContactEmail.AllColumns)
	return db.ExecuteOneTx[model.ContactEmail](ctx, txn, statement)
}

func ContactEmailFromAddress(ctx context.Context, txn db.Ex, address string) (model.ContactEmail, error) {
	statement := table.ContactEmail.SELECT(
		table.ContactEmail.AllColumns,
	).FROM(table.ContactEmail).
		WHERE(table.ContactEmail.Address.EQ(postgres.String(address)))
	return db.ExecuteOneTx[model.ContactEmail](ctx, txn, statement)
}
func ContactEmailByContactIDs(ctx context.Context, txn db.Ex, contact_ids []int64) (result map[int64][]model.ContactEmail, err error) {
	sql_ids := make([]postgres.Expression, len(contact_ids))
	for i, contact_id := range contact_ids {
		sql_ids[i] = postgres.Int(contact_id)
	}
	statement := table.ContactEmail.SELECT(
		table.ContactEmail.AllColumns,
	).FROM(table.ContactEmail).
		WHERE(table.ContactEmail.ContactID.IN(sql_ids...))
	rows, err := db.ExecuteManyTx[model.ContactEmail](ctx, txn, statement)
	if err != nil {
		return result, fmt.Errorf("query by contact IDs: %w", err)
	}
	result = make(map[int64][]model.ContactEmail, len(contact_ids))
	for _, contact_id := range contact_ids {
		result[contact_id] = make([]model.ContactEmail, 0)
	}
	for _, row := range rows {
		id := int64(row.ContactID)
		cur := result[id]
		cur = append(cur, row)
		result[id] = cur
	}
	return result, nil
}
func ContactEmailUpdateContactID(ctx context.Context, txn db.Ex, address string, contact_id int64) error {
	statement := table.ContactEmail.UPDATE().
		SET(
			table.ContactEmail.ContactID.SET(postgres.Int(contact_id)),
		).
		WHERE(table.ContactEmail.Address.EQ(postgres.String(address)))
	return db.ExecuteNoneTx(ctx, txn, statement)
}
