import fs from "fs";
import os from "os";
import path from "path";
import { afterEach, describe, expect, it } from "vitest";
import { bundleK6File } from "./index.mjs";

const cleanups = [];

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

describe("k6 bundler", () => {
  it("bundles root package imports for k6 execution", async () => {
    const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "testkit-bundle-"));
    cleanups.push(() => fs.rmSync(tmpDir, { force: true, recursive: true }));

    const sourceFile = path.join(tmpDir, "health.js");
    fs.writeFileSync(
      sourceFile,
      [
        'import { defineHttpSuite, json } from "@elench/testkit";',
        'import { check } from "k6";',
        "const suite = defineHttpSuite(({ rawReq }) => {",
        '  const res = rawReq("GET", "/health");',
        "  check(json(res), {",
        '    "has status": (body) => typeof body.status === "string",',
        "  });",
        "});",
        "export const options = suite.options;",
        "export const setup = suite.setup;",
        "export default suite.exec;",
        "",
      ].join("\n")
    );

    const bundledFile = await bundleK6File({
      productDir: tmpDir,
      serviceName: "api",
      sourceFile,
    });

    const bundled = fs.readFileSync(bundledFile, "utf8");
    expect(bundled).toContain("defineHttpSuite");
    expect(bundled).toContain('import { check } from "k6"');
  });

  it("bundles subpath package imports for DAL execution", async () => {
    const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "testkit-bundle-"));
    cleanups.push(() => fs.rmSync(tmpDir, { force: true, recursive: true }));

    const sourceFile = path.join(tmpDir, "dal.js");
    fs.writeFileSync(
      sourceFile,
      [
        'import { defineDalSuite } from "@elench/testkit/k6";',
        "const suite = defineDalSuite(({ db }) => {",
        '  db.query("SELECT 1");',
        "});",
        "export const options = suite.options;",
        "export const setup = suite.setup;",
        "export default suite.exec;",
        "",
      ].join("\n")
    );

    const bundledFile = await bundleK6File({
      productDir: tmpDir,
      serviceName: "api",
      sourceFile,
    });

    const bundled = fs.readFileSync(bundledFile, "utf8");
    expect(bundled).toContain("defineDalSuite");
    expect(bundled).toContain('import sql from "k6/x/sql"');
  });
});
