import test from "node:test";
import assert from "node:assert/strict";
import { execFile } from "node:child_process";
import { mkdir, mkdtemp, readFile, readdir, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { dirname, join } from "node:path";
import { fileURLToPath } from "node:url";
import { promisify } from "node:util";

const execFileAsync = promisify(execFile);
const repositoryRoot = dirname(dirname(fileURLToPath(import.meta.url)));
const pwaRoot = join(repositoryRoot, "apps", "pwa");
const viteCli = join(repositoryRoot, "node_modules", "vite", "bin", "vite.js");

async function collectProductionText(directory) {
  const entries = await readdir(directory, { withFileTypes: true });
  const contents = await Promise.all(entries.map(async (entry) => {
    const path = join(directory, entry.name);
    if (entry.isDirectory()) return collectProductionText(path);
    if (!/\.(?:html|js)$/.test(entry.name)) return "";
    return readFile(path, "utf8");
  }));
  return contents.flat(Infinity).join("\n");
}

test("production PWA omits the developer authentication bypass", async (context) => {
  const { assertProductionPwa } = await import("./release-pwa-policy.mjs");
  const output = await mkdtemp(join(tmpdir(), "crm-production-pwa-"));
  context.after(() => rm(output, { recursive: true, force: true }));

  await execFileAsync(process.execPath, [viteCli, "build", "--outDir", output, "--emptyOutDir"], {
    cwd: pwaRoot,
    windowsHide: true
  });

  const productionText = await collectProductionText(output);
  assert.doesNotMatch(productionText, /connection-dev-bypass/);
  assert.doesNotMatch(productionText, /Continue in developer mode/);
  assert.doesNotMatch(productionText, /개발자 모드로 계속/);
  assert.ok((await assertProductionPwa({ pwaDir: output })).files > 0);
});

test("production PWA policy rejects development artifacts without leaking evidence", async (context) => {
  const { assertProductionPwa } = await import("./release-pwa-policy.mjs");
  const cases = [
    { name: "source map", file: "assets/app.js.map", content: "{}" },
    { name: "Vite client", file: "index.html", content: '<script type="module" src="/@vite/client"></script>' },
    { name: "React refresh", file: "assets/app.js", content: "import 'react-refresh/runtime';" },
    { name: "developer bypass", file: "assets/app.js", content: "connection-dev-bypass" },
    { name: "ES module developer bypass", file: "assets/app.mjs", content: "connection-dev-bypass" },
    { name: "CommonJS developer bypass", file: "assets/app.cjs", content: "connection-dev-bypass" },
    { name: "English developer label", file: "assets/app.js", content: "Continue in developer mode" },
    { name: "Korean developer label", file: "assets/app.js", content: "개발자 모드로 계속" },
    { name: "invalid UTF-8 JavaScript", file: "assets/app.js", content: Buffer.from([0xff, 0xfe, 0xfd]) }
  ];

  for (const fixture of cases) {
    await context.test(fixture.name, async (testContext) => {
      const directory = await mkdtemp(join(tmpdir(), "crm-pwa-policy-reject-"));
      testContext.after(() => rm(directory, { recursive: true, force: true }));
      const path = join(directory, fixture.file);
      await mkdir(dirname(path), { recursive: true });
      await writeFile(path, fixture.content);

      await assert.rejects(
        assertProductionPwa({ pwaDir: directory }),
        (error) => error?.message === "release_pwa_development_artifact" &&
          error.stack === "release_pwa_development_artifact"
      );
    });
  }
});

test("production PWA policy accepts safe localhost origins", async (context) => {
  const { assertProductionPwa } = await import("./release-pwa-policy.mjs");
  const directory = await mkdtemp(join(tmpdir(), "crm-pwa-policy-valid-"));
  context.after(() => rm(directory, { recursive: true, force: true }));
  await mkdir(join(directory, "assets"), { recursive: true });
  await writeFile(join(directory, "index.html"), "<main>Code Remote Manager</main>");
  await writeFile(
    join(directory, "assets", "app.js"),
    'const backend = "http://127.0.0.1:43110"; const nativeOrigin = "https://localhost";'
  );
  await writeFile(join(directory, "assets", "app.css"), ".connection-dev-bypass{display:block}");

  assert.deepEqual(await assertProductionPwa({ pwaDir: directory }), { files: 3 });
});
