/**
 * Loads apps/edr-passenger-api/.env.test into process.env BEFORE the Nest AppModule boots.
 * Registered as a jest `setupFile` (runs per test file, before the framework and before any
 * `Test.createTestingModule`). Zero-dependency KEY=VALUE parser — dotenv is not a direct dep here.
 * Existing process.env values win (so CI can override the DB URL without editing the file).
 */
import { existsSync, readFileSync } from "node:fs";
import { join } from "node:path";

// Prefer a local (gitignored) .env.test; fall back to the tracked .env.test.example so a fresh
// checkout of the branch runs the suites without a manual copy step.
const localPath = join(__dirname, "..", "..", ".env.test");
const examplePath = join(__dirname, "..", "..", ".env.test.example");
const envPath = existsSync(localPath) ? localPath : examplePath;

try {
  const raw = readFileSync(envPath, "utf8");
  for (const line of raw.split("\n")) {
    const trimmed = line.trim();
    if (!trimmed || trimmed.startsWith("#")) continue;
    const eq = trimmed.indexOf("=");
    if (eq === -1) continue;
    const key = trimmed.slice(0, eq).trim();
    let value = trimmed.slice(eq + 1).trim();
    // strip surrounding quotes if present
    if (
      (value.startsWith('"') && value.endsWith('"')) ||
      (value.startsWith("'") && value.endsWith("'"))
    ) {
      value = value.slice(1, -1);
    }
    if (process.env[key] === undefined) process.env[key] = value;
  }
} catch (err) {
  // Surface loudly — a missing .env.test means every suite would boot against the wrong DB.
  throw new Error(
    `[load-env] could not read ${envPath}: ${(err as Error).message}`,
  );
}
