package script

import (
	"context"
	"testing"

	tengo "github.com/d5/tengo/v2"

	"git.autistici.org/ai3/tools/iprep/ext"
)

type dummyExtSource map[string]int64

func (s dummyExtSource) LookupIP(ip string) (tengo.Object, error) {
	value, ok := s[ip]
	if !ok {
		return tengo.UndefinedValue, nil
	}
	return &tengo.Int{Value: value}, nil
}

func runTestScript(t *testing.T, src string, expected float64, extSrcs map[string]ext.ExternalSource) {
	s, err := NewScript([]byte(src))
	if err != nil {
		t.Fatalf("NewScript: %v", err)
	}
	m := map[string]int64{
		"test":  10,
		"test2": 2,
	}

	score, err := s.RunIP(context.Background(), "1.2.3.4", m, 3600, extSrcs)
	if err != nil {
		t.Fatalf("runScript: %v", err)
	}
	if score != expected {
		t.Fatalf("bad score, expected %f got %f", expected, score)
	}
}

func TestScript_WithLookup(t *testing.T) {
	runTestScript(t, `
score = counts["test"] / 2 + counts["test2"] + counts["test3"]
//score = 7
`, 7, nil)
}

func TestScript_FloatScore(t *testing.T) {
	runTestScript(t, `
score = 7.0
`, 7, nil)
}

func TestScript_IntScore(t *testing.T) {
	runTestScript(t, `
score = 7
`, 7, nil)
}

func TestScript_StringScore(t *testing.T) {
	runTestScript(t, `
score = "7"
`, 7, nil)
}

func TestScript_ExternalSource(t *testing.T) {
	runTestScript(t, `
score = ext("test", ip)
`, 7, map[string]ext.ExternalSource{
		"test": dummyExtSource{
			"1.2.3.4": 7,
		},
	})
}