package public

import (
	"context"
	"errors"
	"fmt"

	"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/public/model"
	"source.gleipnir.technology/Gleipnir/nidus-sync/db/gen/nidus-sync/public/table"
)

func CommunicationInsert(ctx context.Context, txn db.Ex, m model.Communication) (model.Communication, error) {
	statement := table.Communication.INSERT(table.Communication.MutableColumns).
		MODEL(m).
		RETURNING(table.Communication.AllColumns)
	return db.ExecuteOneTx[model.Communication](ctx, txn, statement)
}
func CommunicationFromID(ctx context.Context, txn db.Ex, comm_id int64) (model.Communication, error) {
	statement := table.Communication.SELECT(
		table.Communication.AllColumns,
	).FROM(table.Communication).
		WHERE(table.Communication.ID.EQ(postgres.Int(comm_id)))
	return db.ExecuteOneTx[model.Communication](ctx, txn, statement)
}
func CommunicationsFromOrganization(ctx context.Context, txn db.Ex, org_id int64) ([]model.Communication, error) {
	statement := table.Communication.SELECT(
		table.Communication.AllColumns,
	).FROM(table.Communication).
		WHERE(table.Communication.OrganizationID.EQ(postgres.Int(org_id))).
		ORDER_BY(table.Communication.Created.DESC())
	return db.ExecuteManyTx[model.Communication](ctx, txn, statement)
}
func CommunicationFromReportID(ctx context.Context, txn db.Ex, report_id int64) (*model.Communication, error) {
	statement := table.Communication.SELECT(
		table.Communication.AllColumns,
	).FROM(table.Communication).
		WHERE(table.Communication.SourceReportID.EQ(postgres.Int(report_id)))
	row, err := db.ExecuteOneTx[model.Communication](ctx, txn, statement)
	if err != nil {
		if errors.Is(err, db.ErrNoRows) {
			return nil, nil
		}
		return nil, fmt.Errorf("query communication from report %d: %w", report_id, err)
	}
	return &row, nil
}
func CommunicationSetStatus(ctx context.Context, txn db.Ex, org_id int64, comm_id int64, status model.Communicationstatus) error {
	statement := table.Communication.UPDATE().
		SET(
			table.Communication.Status.SET(postgres.NewEnumValue(status.String())),
		).
		WHERE(table.Communication.OrganizationID.EQ(postgres.Int(org_id)).AND(
			table.Communication.ID.EQ(postgres.Int(comm_id))))
	return db.ExecuteNoneTx(ctx, txn, statement)
}
