import fs from "fs";
import os from "os";
import path from "path";
import { pathToFileURL } from "url";
import { afterEach, describe, expect, it } from "vitest";
import {
  ensurePlaywrightTestConfig,
  findPlaywrightConfig,
  resolvePlaywrightOutputDir,
} from "./playwright-config.mjs";

const cleanups = [];

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

function makeTempDir(prefix) {
  const dir = fs.mkdtempSync(path.join(os.tmpdir(), prefix));
  cleanups.push(() => fs.rmSync(dir, { recursive: true, force: true }));
  return dir;
}

describe("runner-playwright-config", () => {
  it("uses a shard-local output directory under the state dir", async () => {
    const productDir = makeTempDir("testkit-playwright-product-");
    const stateDir = path.join(productDir, ".testkit", "worker-3");
    const cwd = path.join(productDir, "frontend");
    fs.mkdirSync(cwd, { recursive: true });
    fs.writeFileSync(
      path.join(cwd, "playwright.config.mjs"),
      "export default { outputDir: 'shared-test-results' };\n"
    );

    const configPath = ensurePlaywrightTestConfig(
      { productDir, stateDir },
      cwd,
      ["frontend/__testkit__/homepage/homepage.pw.testkit.ts"]
    );
    const generated = await import(pathToFileURL(configPath).href + `?t=${Date.now()}`);

    const expectedOutputDir = resolvePlaywrightOutputDir(stateDir);
    expect(generated.default.outputDir).toBe(expectedOutputDir);
    expect(fs.existsSync(expectedOutputDir)).toBe(true);
    expect(fs.readFileSync(configPath, "utf8")).toContain(
      `outputDir: ${JSON.stringify(expectedOutputDir)}`
    );
  });

  it("finds a supported playwright config file", () => {
    const cwd = makeTempDir("testkit-playwright-cwd-");
    fs.writeFileSync(path.join(cwd, "playwright.config.ts"), "export default {};\n");

    expect(findPlaywrightConfig(cwd)).toBe(path.join(cwd, "playwright.config.ts"));
  });
});
