package policycatalog

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

func TestScan(t *testing.T) {
	t.Parallel()
	dir := t.TempDir()
	refundBody := `package acp.refund
default decision = {
	"decision": "allow",
	"reason": "default_allow",
	"policy": "acp/refund",
}
`
	if err := os.WriteFile(filepath.Join(dir, "refund.rego"), []byte(refundBody), 0o644); err != nil {
		t.Fatal(err)
	}
	if err := os.WriteFile(filepath.Join(dir, "router.rego"), []byte("package acp\n"), 0o644); err != nil {
		t.Fatal(err)
	}
	if err := os.WriteFile(filepath.Join(dir, "policies_test.rego"), []byte("package acp_test\n"), 0o644); err != nil {
		t.Fatal(err)
	}

	got, err := Scan(dir)
	if err != nil {
		t.Fatal(err)
	}
	if len(got) != 2 {
		t.Fatalf("len=%d want 2: %#v", len(got), got)
	}
	var refund, router *Entry
	for i := range got {
		switch got[i].Domain {
		case "refund":
			refund = &got[i]
		case "router":
			router = &got[i]
		}
	}
	if refund == nil || router == nil {
		t.Fatalf("missing entries: %#v", got)
	}
	if refund.PolicyID != "acp/refund" || refund.EntryKind != "module" || refund.RuleCount != 1 {
		t.Fatalf("refund: %#v", refund)
	}
	if router.EntryKind != "router" || router.PolicyID != "acp/router" {
		t.Fatalf("router: %#v", router)
	}
}
