import { afterEach, beforeEach, describe, expect, test } from "bun:test";
import { mkdir, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";

import { validateVersion } from "../../scripts/bump-version-logic";

describe("build 版本注入", () => {
  test("validateVersion 接受有效版本", () => {
    expect(() => validateVersion("0.1.0")).not.toThrow();
    expect(() => validateVersion("1.2.3")).not.toThrow();
  });

  test("validateVersion 拒绝无效版本", () => {
    expect(() => validateVersion("invalid")).toThrow();
    expect(() => validateVersion("1.0.0-beta.1")).toThrow();
  });
});

describe("server-entry 版本字面量", () => {
  let tempDir: string;

  beforeEach(async () => {
    tempDir = join(tmpdir(), `build-version-test-${Date.now()}`);
    await mkdir(tempDir, { recursive: true });
  });

  afterEach(async () => {
    await rm(tempDir, { force: true, recursive: true });
  });

  test("生成的 server-entry 包含版本字面量", async () => {
    const version = "0.1.0";
    const serverEntryTs = [
      `import { bootstrap } from "../src/server/bootstrap";`,
      `import { readRuntimeConfig } from "../src/server/config";`,
      `import { staticAssets } from "./static-assets";`,
      "",
      `const APP_VERSION = "${version}" as const;`,
      "",
      `async function main() {`,
      `  const { configPath } = readRuntimeConfig();`,
      `  await bootstrap({ configPath, mode: "production", staticAssets, version: APP_VERSION });`,
      `}`,
      "",
      `void main().catch((error) => {`,
      `  console.error("启动失败:", error instanceof Error ? error.message : error);`,
      `  process.exit(1);`,
      `});`,
      "",
    ].join("\n");

    await writeFile(join(tempDir, "server-entry.ts"), serverEntryTs);

    const content = await Bun.file(join(tempDir, "server-entry.ts")).text();
    expect(content).toContain(`const APP_VERSION = "${version}"`);
    expect(content).toContain("version: APP_VERSION");
  });

  test("版本字面量不依赖外部 package.json", async () => {
    const serverEntryTs = [`const APP_VERSION = "0.1.0" as const;`].join("\n");

    await writeFile(join(tempDir, "server-entry.ts"), serverEntryTs);

    const content = await Bun.file(join(tempDir, "server-entry.ts")).text();
    expect(content).not.toContain("package.json");
    expect(content).not.toContain("Bun.file");
    expect(content).toContain('"0.1.0"');
  });
});
