package common

import (
	"encoding/json"

	"github.com/fiskerinc/cloud-services/pkg/grpc/kafka_grpc"
	"github.com/pkg/errors"
)

type TRexError struct {
	Code    int                `json:"code"`
	Message []TRexErrorMessage `json:"message"`
}

type TRexErrorMessage struct {
	Context     []string `json:"context"`
	Description string   `json:"description"`
}


func (te *TRexError) ToGrpc(data MessageRawJSON)(*kafka_grpc.TRexLogs_BatchPayload, error){
	var logs TRexError
	err := json.Unmarshal(data.Data, &logs)
	if err != nil {
		return nil, errors.WithStack(err)
	}
	var msg kafka_grpc.TRexError
	msg.Message = make([]*kafka_grpc.TRexErrorMessage, len(logs.Message))
	msg.Code = int64(logs.Code)
	for i, log := range logs.Message{
		msg.Message[i] = &kafka_grpc.TRexErrorMessage{
			Context:     log.Context,
			Description: log.Description,
		}
	}
	nested := kafka_grpc.TRexLogs_BatchPayload_Error{
		Error: &msg,
	}
	batchPayload := kafka_grpc.TRexLogs_BatchPayload{
		Handler: data.Handler,
		TRexMessage: &nested,
		Version: data.Version,
	}

	return &batchPayload, nil
}