package main

import (
	"encoding/json"
	"fmt"

	"jobarranger2/src/libs/golibs/common"
	"jobarranger2/src/libs/golibs/config_reader/server"
)

var (
	JAZ_1_VERSION = 1
	JAZ_2_VERSION = 2
)

func jaTelegramSetErr(responseObj *common.ResponseData, message, preUid string) error {
	funcname := "jaTelegramSetErr"
	TrapperLogger.JaLog("JATRAPPERMANAGER400001", funcname)
	// Validate input
	if responseObj == nil || message == "" {
		return fmt.Errorf("invalid input: responseObj or message is nil/empty")
	}

	responseObj.Result = common.JobResultRespStatusFailed
	responseObj.Message = &message

	if preUid != "" {
		responseObj.PreUniqueID = &preUid
	}

	return nil
}
func jaTrapperReply(jobnetPayload common.EventData, con *common.NetConnection, responseObj common.ResponseData) error {
	funcname := "jaTrapperReply"
	TrapperLogger.JaLog("JATRAPPERMANAGER400001", funcname)

	var err error

	con.SetSendTimeout(int64(server.Options.Timeout))

	if jobnetPayload.TCPMessage.JazVersion == nil {
		// Jaz 1: Send the TCPMessage itself with updated Data
		// fmt.Println(responseObj)
		jobnetPayload.TCPMessage.Data = &responseObj

		// Marshal the response object to JSON for readable logging
		respBytes, _ := json.Marshal(jobnetPayload.TCPMessage)
		TrapperLogger.JaLog("JATRAPPERMANAGER400006", string(respBytes))
		err = con.Send(jobnetPayload.TCPMessage)
	} else {
		// Others: Send the whole EventData with Data as a pointer
		jobnetPayload.TCPMessage.Data = &responseObj

		// Marshal the response object to JSON for readable logging
		respBytes, _ := json.Marshal(jobnetPayload)

		TrapperLogger.JaLog("JATRAPPERMANAGER400007", string(respBytes))
		err = con.Send(jobnetPayload)
	}

	if err != nil {
		TrapperLogger.JaLog("JATRAPPERMANAGER200001", funcname, err.Error())
		return fmt.Errorf("jaTrapperReply failed")
	}

	return nil
}
