package comms

import (
	"context"

	"github.com/Gleipnir-Technology/jet/postgres"
	"source.gleipnir.technology/Gleipnir/nidus-sync/db"
	"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 TextLogInsert(ctx context.Context, txn db.Ex, m model.TextLog) (model.TextLog, error) {
	statement := table.TextLog.INSERT(
		table.TextLog.MutableColumns,
	).MODEL(m).
		RETURNING(table.TextLog.AllColumns)
	return db.ExecuteOneTx[model.TextLog](ctx, txn, statement)
}
func TextLogFromID(ctx context.Context, txn db.Ex, id int64) (model.TextLog, error) {
	statement := table.TextLog.SELECT(
		table.TextLog.AllColumns,
	).FROM(table.TextLog).
		WHERE(table.TextLog.ID.EQ(postgres.Int(id)))
	return db.ExecuteOneTx[model.TextLog](ctx, txn, statement)
}
func TextLogsFromPhoneNumber(ctx context.Context, txn db.Ex, number string) ([]model.TextLog, error) {
	statement := table.TextLog.SELECT(
		table.TextLog.AllColumns,
	).FROM(table.TextLog).
		WHERE(table.TextLog.Source.EQ(postgres.String(number)).OR(
			table.TextLog.Destination.EQ(postgres.String(number)))).
		ORDER_BY(table.TextLog.Created.DESC())
	return db.ExecuteManyTx[model.TextLog](ctx, txn, statement)
}
func TextLogWelcomeFromDestination(ctx context.Context, txn db.Ex, destination string) ([]model.TextLog, error) {
	statement := table.TextLog.SELECT(
		table.TextLog.AllColumns,
	).FROM(table.TextLog).
		WHERE(table.TextLog.Destination.EQ(postgres.String(destination)).AND(
			table.TextLog.IsWelcome.EQ(postgres.Bool(true))))
	return db.ExecuteManyTx[model.TextLog](ctx, txn, statement)
}
func TextLogUpdate(ctx context.Context, txn db.Ex, id int64, twilio_sid string, twilio_status string) error {
	statement := table.TextLog.UPDATE(
		table.TextLog.TwilioSid,
		table.TextLog.TwilioStatus,
	).SET(
		table.TextLog.TwilioSid.SET(postgres.String(twilio_sid)),
		table.TextLog.TwilioStatus.SET(postgres.String(twilio_status)),
	).WHERE(table.TextLog.ID.EQ(postgres.Int(id)))
	return db.ExecuteNoneTx(ctx, txn, statement)
}
