package mongoext

import (
	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/mongo"
)

// FixTextSearchPipeline moves {$match:{$text:{$search}}} entries to the front of the pipeline (otherwise its an mongo error)
func FixTextSearchPipeline(pipeline mongo.Pipeline) mongo.Pipeline {

	dget := func(v bson.D, k string) (bson.M, bool) {
		for _, e := range v {
			if e.Key == k {
				if mv, ok := e.Value.(bson.M); ok {
					return mv, true
				}
			}
		}
		return nil, false
	}
	mget := func(v bson.M, k string) (bson.M, bool) {
		for ekey, eval := range v {
			if ekey == k {
				if mv, ok := eval.(bson.M); ok {
					return mv, true
				}
			}
		}
		return nil, false
	}

	result := make([]bson.D, 0, len(pipeline))

	for _, entry := range pipeline {

		if v0, ok := dget(entry, "$match"); ok {
			if v1, ok := mget(v0, "$text"); ok {
				if _, ok := v1["$search"]; ok {
					result = append([]bson.D{entry}, result...)
					continue
				}
			}
		}

		result = append(result, entry)
	}

	return result
}