package utils

import (
	"github.com/itchyny/gojq"
	"github.com/porter-dev/porter/internal/templater"
)

// NewQuery constructs a templater.TemplateReaderQuery by parsing the jsonpath
// query string
func NewQuery(key, query string) (*templater.TemplateReaderQuery, error) {
	jquery, err := gojq.Parse(query)

	if err != nil {
		return nil, err
	}

	return &templater.TemplateReaderQuery{
		Key:         key,
		QueryString: query,
		Template:    jquery,
	}, nil
}

// QueryValues iterates through a map[string]interface{} and executes a query,
// returning a map of the query name to the returned data
func QueryValues(
	values map[string]interface{},
	queries []*templater.TemplateReaderQuery,
) (map[string]interface{}, error) {
	res := make(map[string]interface{})

	// iterate through all registered queries, add to resulting map
	for _, query := range queries {
		iter := query.Template.Run(values)

		queryRes := make([]interface{}, 0)

		for {
			v, ok := iter.Next()

			if !ok {
				break
			}

			if err, ok := v.(error); ok {
				return nil, err
			}

			queryRes = append(queryRes, v)
		}

		res[query.Key] = queryRes
	}

	return res, nil
}
