/*
analysis:

	对访问 es 的 api 做一个初步的分类:
	- 是不是一次 client 的请求
	- 操作的 indixes 是哪些
	- 使用的对应的 es 的 api 是哪个?
*/
package analysis

import (
	"strings"

	"esway/internal/log"
	"esway/internal/model"
	"esway/internal/opt"

	"github.com/loveuer/nf"
	"github.com/samber/lo"
)

const LocalKey = "es"

func New() nf.HandlerFunc {
	return func(c *nf.Ctx) error {
		local := &model.ESReqRes{
			ClientRequest: false,
			Path:          c.Path(),
			Method:        c.Method(),
			Indixes:       []string{},
			Api:           model.ESApiUnknown,
		}

		defer func() {
			c.Locals(LocalKey, local)
			if opt.Cfg.Debug {
				log.Debug(c.Context(), "middleware.analysis: local = %#v", *local)
			}
		}()

		if len(local.Path) == 0 || strings.HasPrefix(local.Path, "/_") || strings.HasPrefix(local.Method, "/.") {
			return c.Next()
		}

		paths := strings.Split(local.Path[1:], "/")

		local.ClientRequest = true
		local.Indixes = lo.FilterMap(
			strings.Split(paths[0], ","),
			func(item string, idx int) (string, bool) {
				val := strings.TrimSpace(item)
				return val, val != ""
			},
		)

		if len(paths) < 2 {
			return c.Next()
		}

		switch paths[1] {
		case "_doc":
		case "_search":
		case "_update":
		case "_update_by_query":
		}

		return c.Next()
	}
}