package audit

import (
	"go/ast"
	"go/parser"
	"go/token"
	"path/filepath"
	"strconv"
	"strings"
	"testing"
)

func TestGenericAuditDoesNotOwnApprovalAdapter(t *testing.T) {
	allowedApprovalDeclarations := map[string]bool{}
	disallowedAppVocabulary := disallowedAuditAppVocabulary()

	files, err := filepath.Glob("*.go")
	if err != nil {
		t.Fatalf("glob audit sources: %v", err)
	}
	for _, file := range files {
		if strings.HasSuffix(file, "_test.go") {
			continue
		}

		fset := token.NewFileSet()
		parsed, err := parser.ParseFile(fset, file, nil, 0)
		if err != nil {
			t.Fatalf("parse %s: %v", file, err)
		}

		for _, decl := range parsed.Decls {
			switch decl := decl.(type) {
			case *ast.FuncDecl:
				assertNotAppActionVocabularyDeclaration(t, file, decl.Name.Name, allowedApprovalDeclarations, disallowedAppVocabulary)
			case *ast.GenDecl:
				for _, spec := range decl.Specs {
					switch spec := spec.(type) {
					case *ast.TypeSpec:
						assertNotAppActionVocabularyDeclaration(t, file, spec.Name.Name, allowedApprovalDeclarations, disallowedAppVocabulary)
					case *ast.ValueSpec:
						for _, name := range spec.Names {
							assertNotAppActionVocabularyDeclaration(t, file, name.Name, allowedApprovalDeclarations, disallowedAppVocabulary)
						}
						for i, value := range spec.Values {
							declarationName := ""
							if i < len(spec.Names) {
								declarationName = spec.Names[i].Name
							}
							assertNotAppActionVocabularyValue(t, file, declarationName, value, allowedApprovalDeclarations, disallowedAppVocabulary)
						}
					}
				}
			}
		}
	}
}

func TestAuditActionRemainsOpenStringVocabulary(t *testing.T) {
	event := AuditEvent{
		ObjectApiName: "AnyObject",
		RecordId:      "record-1",
		Action:        AuditAction("APPROVE"),
		ChangedById:   "user-1",
		Entrypoint:    EntrypointRestAPI,
		Outcome:       OutcomeSuccess,
	}

	if err := event.Validate(); err != nil {
		t.Fatalf("Validate() rejected app-owned audit action string: %v", err)
	}
}

func TestDisallowedAuditAppVocabularyCoversNounForms(t *testing.T) {
	disallowedAppVocabulary := disallowedAuditAppVocabulary()
	for _, text := range []string{"ActionConversion", "CONVERSION", "ActionRejection", "REJECTION", "ActionSubmission", "SUBMISSION"} {
		if term, ok := matchingDisallowedAppVocabulary(text, disallowedAppVocabulary); !ok {
			t.Fatalf("%s did not match disallowed audit app vocabulary; got term %q", text, term)
		}
	}
}

func disallowedAuditAppVocabulary() []string {
	return []string{
		"approve",
		"approval",
		"convert",
		"conversion",
		"reject",
		"rejection",
		"submit",
		"submission",
	}
}

func assertNotAppActionVocabularyDeclaration(t *testing.T, file, name string, allowed map[string]bool, disallowed []string) {
	t.Helper()
	if allowed[name] {
		return
	}
	if term, ok := matchingDisallowedAppVocabulary(name, disallowed); ok {
		t.Fatalf("%s declares %s; app-specific audit action vocabulary (%s) must live outside generic audit", file, name, term)
	}
}

func assertNotAppActionVocabularyValue(t *testing.T, file, name string, value ast.Expr, allowed map[string]bool, disallowed []string) {
	t.Helper()
	if allowed[name] {
		return
	}

	basicLit, ok := value.(*ast.BasicLit)
	if !ok || basicLit.Kind != token.STRING {
		return
	}
	unquoted, err := strconv.Unquote(basicLit.Value)
	if err != nil {
		t.Fatalf("unquote %s literal %s: %v", file, basicLit.Value, err)
	}
	if term, ok := matchingDisallowedAppVocabulary(unquoted, disallowed); ok {
		t.Fatalf("%s declares string value %q; app-specific audit action vocabulary (%s) must live outside generic audit", file, unquoted, term)
	}
}

func matchingDisallowedAppVocabulary(text string, disallowed []string) (string, bool) {
	lower := strings.ToLower(text)
	for _, term := range disallowed {
		if strings.Contains(lower, term) {
			return term, true
		}
	}
	return "", false
}
