package linthost

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

// TestNodeConfigLoaderEnvPrependsNearestNodeModules verifies NODE_PATH loader metadata.
//
// JavaScript and TypeScript config loading run in subprocesses. The loader
// environment should prepend the nearest project node_modules path while
// preserving an already configured NODE_PATH value.
//
// This scenario exercises nodeConfigLoaderEnv, findNearestNodeModules, and the
// setEnv replacement branch through the same path used by config subprocesses.
//
// 1. Create a project tree with a node_modules directory above the config file.
// 2. Seed NODE_PATH with an existing value.
// 3. Assert the generated environment prepends the nearest node_modules path.
//
// @evidence contracts/testing.md#behavioral-verification nodeConfigLoaderEnv produces NODE_PATH containing the nearest fixture node_modules before the existing already-present entry.
// @evidence contracts/testing.md#independent-expectations Node path-list ordering requires the local module search root first while preserving configured entries; the fixture path and OS PathListSeparator define the independent complete expected environment entry.
// @evidence contracts/testing.md#distinguishing-cases Owns nested config discovery with a pre-existing NODE_PATH value; direct setEnv tests cover absent-key insertion and replacement.
// @evidence contracts/testing.md#execution-ownership This discoverable Go entry owns the case described above. An authored temporary node_modules directory and scoped NODE_PATH value reach nodeConfigLoaderEnv in-process; the complete returned environment entry is inspected without spawning Node or installing dependencies.
func TestNodeConfigLoaderEnvPrependsNearestNodeModules(t *testing.T) {
  root := t.TempDir()
  nodeModules := filepath.Join(root, "node_modules")
  if err := os.MkdirAll(nodeModules, 0o755); err != nil {
    t.Fatalf("MkdirAll: %v", err)
  }
  config := filepath.Join(root, "packages", "app", "lint.config.js")
  writeFile(t, config, "export default {};")
  t.Setenv("NODE_PATH", "already-present")

  env := nodeConfigLoaderEnv(config)
  want := "NODE_PATH=" + nodeModules + string(os.PathListSeparator) + "already-present"
  for _, entry := range env {
    if entry == want {
      return
    }
  }
  matches := []string{}
  for _, entry := range env {
    if strings.HasPrefix(entry, "NODE_PATH=") {
      matches = append(matches, entry)
    }
  }
  t.Fatalf("NODE_PATH overlay %q not found in env entries containing NODE_PATH: %v", want, matches)
}
