package sshd

import (
	"encoding/json"
	"fmt"

	"hnyfkj.com.cn/rtu/linux/utils/jsonrpc2"
	"hnyfkj.com.cn/rtu/linux/utils/shell"
)

func buildResp(req *jsonrpc2.Request, result any, err error) *jsonrpc2.Response {
	if err != nil {
		return jsonrpc2.BuildError(req, -32700, err.Error())
	}

	resp, err := jsonrpc2.BuildResult(req, result)
	if err != nil {
		return jsonrpc2.BuildError(req, jsonrpc2.ErrInternal, "")
	}

	return resp
}

func parseShellExecuteParams(params json.RawMessage) (shell.ExecuteParams, error) {
	if len(params) == 0 {
		return shell.ExecuteParams{}, fmt.Errorf("missing params")
	}

	var p shell.ExecuteParams
	if err := json.Unmarshal(params, &p); err != nil {
		return shell.ExecuteParams{}, err
	}

	return p, nil
}
