// security_gosec_g101_test.go — verifies that a hardcoded
// credential in a Go file (G101 pattern) would be caught by gosec.
// We don't run gosec here (it requires the external binary); we
// assert that the gosec configuration (in .golangci.yml + the
// .coreci.yml `validate` stage) requires it. The fixture file
// `testdata/hardcoded_creds.go` carries a literal G101 pattern
// that, if reintroduced into production code, would fail CI.
//
// The fixture is in `internal/security/testdata/` so the
// .gitleaks.toml and gosec path-excludes can allowlist it for
// testing purposes only.
package security

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

// TestHardcodedCredsFixturePresent is a meta-test: the fixture
// file MUST exist; if it's missing, the test fails loudly. The
// fixture carries a literal `apiKey := "..."` pattern (G101) so
// that any tooling run on the orca repo that finds it (after
// allowlist removal) will fail.
func TestHardcodedCredsFixturePresent(t *testing.T) {
	root, err := findRepoRoot()
	if err != nil {
		t.Fatalf("findRepoRoot: %v", err)
	}
	path := filepath.Join(root, "internal", "security", "testdata", "hardcoded_creds.go")
	body, err := os.ReadFile(path)
	if err != nil {
		t.Fatalf("read fixture: %v (the fixture is required so the G101 pattern is testable)", err)
	}
	if !strings.Contains(string(body), `apiKey := "GOSEC_G101_FIXTURE_VALUE_`) {
		t.Error("fixture is missing the G101 pattern")
	}
}

// TestGosecInstalledInCi confirms the .coreci.yml `validate`
// pipeline installs gosec. We don't run gosec here; we just
// assert the install + run commands are present.
func TestGosecInstalledInCi(t *testing.T) {
	root, err := findRepoRoot()
	if err != nil {
		t.Fatalf("findRepoRoot: %v", err)
	}
	body, err := os.ReadFile(filepath.Join(root, ".coreci.yml"))
	if err != nil {
		t.Fatalf("read: %v", err)
	}
	s := string(body)
	if !strings.Contains(s, "go install github.com/securego/gosec") {
		t.Error(".coreci.yml validate pipeline must install gosec")
	}
	if !strings.Contains(s, "gosec -fmt") {
		t.Error(".coreci.yml validate pipeline must run gosec")
	}
}

// TestGovulncheckOfflineMode confirms the offline mode env var
// is set in .coreci.yml. REQ-027.
func TestGovulncheckOfflineMode(t *testing.T) {
	root, err := findRepoRoot()
	if err != nil {
		t.Fatalf("findRepoRoot: %v", err)
	}
	body, err := os.ReadFile(filepath.Join(root, ".coreci.yml"))
	if err != nil {
		t.Fatalf("read: %v", err)
	}
	s := string(body)
	if !strings.Contains(s, "GOFLAGS: -mod=mod") {
		t.Error(".coreci.yml must set GOFLAGS=-mod=mod for offline mode (REQ-027)")
	}
	if !strings.Contains(s, "govulncheck") {
		t.Error(".coreci.yml must invoke govulncheck")
	}
}
