package policycatalog

import (
	"os"
	"path/filepath"
	"testing"
)

func TestParseRulesFromSource_refund(t *testing.T) {
	t.Parallel()
	src := `package acp.refund

default decision = {
	"decision": "allow",
	"reason": "refund_within_limits",
	"policy": "acp/refund",
}

decision = {
	"decision": "deny",
	"reason": "refund_amount_exceeds_hard_cap",
	"policy": "acp/refund",
} {
	input.amount > 10000
}
`
	rules := ParseRulesFromSource(src)
	if len(rules) != 2 {
		t.Fatalf("len=%d want 2: %#v", len(rules), rules)
	}
	if !rules[0].IsDefault || rules[0].Decision != "allow" {
		t.Fatalf("default: %#v", rules[0])
	}
	if rules[1].Decision != "deny" || len(rules[1].Conditions) != 1 {
		t.Fatalf("deny: %#v", rules[1])
	}
}

func TestParseRoutesFromSource(t *testing.T) {
	t.Parallel()
	src := `decision = refund.decision {
	input.tool == "refund_api"
}
decision = ledger.decision {
	input.tool == "ledger_api"
}
`
	routes := ParseRoutesFromSource(src)
	if len(routes) != 2 {
		t.Fatalf("len=%d: %#v", len(routes), routes)
	}
	if routes[0].Tool != "refund_api" || routes[0].PolicyID != "acp/refund" {
		t.Fatalf("route0: %#v", routes[0])
	}
}

func TestScan_realPoliciesDir(t *testing.T) {
	t.Parallel()
	dir := filepath.Join("..", "..", "policies")
	if _, err := os.Stat(dir); err != nil {
		t.Skip("policies dir not present")
	}
	got, err := Scan(dir)
	if err != nil {
		t.Fatal(err)
	}
	if len(got) < 7 {
		t.Fatalf("expected several modules, got %d", len(got))
	}
	var refund *Entry
	for i := range got {
		if got[i].Domain == "refund" {
			refund = &got[i]
			break
		}
	}
	if refund == nil || refund.RuleCount < 3 {
		t.Fatalf("refund entry: %#v", refund)
	}
}
