package auditcoverage_test

import (
	"path/filepath"
	"reflect"
	"runtime"
	"testing"

	"github.com/break/junhong_cmp_fiber/internal/governance/auditcoverage"
)

func TestReviewedAuditCoverageManifestMatchesAllRegisteredEntrypoints(t *testing.T) {
	_, currentFile, _, ok := runtime.Caller(0)
	if !ok {
		t.Fatal("无法定位覆盖门禁测试文件")
	}
	root := filepath.Clean(filepath.Join(filepath.Dir(currentFile), "../../../"))
	actual, err := auditcoverage.Scan(root)
	if err != nil {
		t.Fatalf("扫描全系统入口失败：%v", err)
	}
	expected, err := auditcoverage.LoadManifest(filepath.Join(root, ".scratch/tech-global-audit/审计覆盖清单.json"))
	if err != nil {
		t.Fatalf("读取经评审审计覆盖清单失败：%v", err)
	}
	if len(actual) == 0 {
		t.Fatal("入口扫描结果为空，覆盖门禁不可用")
	}
	if !reflect.DeepEqual(expected, actual) {
		t.Fatalf("源码入口与审计覆盖清单不一致：清单 %d 项，源码 %d 项；请重新分类并完成评审后更新清单", len(expected), len(actual))
	}
	for _, entry := range expected {
		if entry.AuditEvent == "" || entry.DomainLedger == "" || entry.IntegrationLog == "" || entry.Outbox == "" ||
			entry.Transaction == "" || entry.FailureStrategy == "" || entry.SensitivePolicy == "" ||
			entry.BeforeAfterPolicy == "" || entry.TestSeam == "" {
			t.Fatalf("入口 %s 存在未分类字段", entry.Key)
		}
		if entry.AuditEvent == "N/A" && entry.NAReason == "" {
			t.Fatalf("入口 %s 的 Audit Event 为 N/A 但缺少理由", entry.Key)
		}
		if entry.AuditEvent != "N/A" && (entry.ActionCode == "" || entry.ActionName == "" || entry.Category == "" ||
			entry.Risk == "" || entry.PrimaryResource == "") {
			t.Fatalf("入口 %s 缺少动作、风险或主要资源", entry.Key)
		}
	}
}
