import fs from "fs";
import os from "os";
import path from "path";
import { afterEach, describe, expect, it } from "vitest";
import { inferEnvFiles, parseDotenvString } from "./env.mjs";

const cleanups = [];

afterEach(() => {
  while (cleanups.length > 0) {
    cleanups.pop()();
  }
});

describe("config env helpers", () => {
  it("parses dotenv content with comments and quoted values", () => {
    expect(
      parseDotenvString(`
        # comment
        FOO=bar
        BAR="quoted value"
        BAZ='single quoted'
      `)
    ).toEqual({
      FOO: "bar",
      BAR: "quoted value",
      BAZ: "single quoted",
    });
  });

  it("infers env files from service cwd and root", () => {
    const productDir = fs.mkdtempSync(path.join(os.tmpdir(), "testkit-env-"));
    cleanups.push(() => fs.rmSync(productDir, { recursive: true, force: true }));
    fs.mkdirSync(path.join(productDir, "apps", "web"), { recursive: true });
    fs.writeFileSync(path.join(productDir, ".env"), "ROOT=1\n");
    fs.writeFileSync(path.join(productDir, "apps", "web", ".env.testkit"), "WEB=1\n");

    expect(inferEnvFiles(productDir, {}, { cwd: "apps/web" })).toEqual(["apps/web/.env.testkit", ".env"]);
  });
});
