// Copyright (c) 2024-2026 Celestino Amoroso (celestino.amoroso@gmail.com).
// All rights reserved.

// operator-in.go
package expr

import (
	"git.portale-stac.it/go-pkg/expr/kern"
	"git.portale-stac.it/go-pkg/expr/scan"
)

//-------- in term

func newInTerm(tk *scan.Token) (inst *scan.Term) {
	return &scan.Term{
		Tk:       *tk,
		Children: make([]*scan.Term, 0, 2),
		Position: scan.PosInfix,
		Priority: scan.PriRelational,
		EvalFunc: evalIn,
	}
}

// func hasKey(d map[any]any, target any) (ok bool) {
// 	_, ok = d[target]
// 	return
// }

func evalIn(ctx kern.ExprContext, opTerm *scan.Term) (v any, err error) {
	var leftValue, rightValue any

	if leftValue, rightValue, err = opTerm.EvalInfix(ctx); err != nil {
		return
	}

	if kern.IsList(rightValue) {
		list, _ := rightValue.(*kern.ListType)
		v = list.IndexDeepSameCmp(leftValue) >= 0
	} else if kern.IsDict(rightValue) {
		dict, _ := rightValue.(*kern.DictType)
		v = dict.HasKey(leftValue)
	} else {
		err = opTerm.ErrIncompatibleTypes(leftValue, rightValue)
	}
	return
}

// init
func init() {
	scan.RegisterTermConstructor(scan.SymKwIn, newInTerm)
}
