import { describe, expect, it } from "vitest";
import {
  createDeterministicZip,
  parseReleaseArguments,
  safeArchivePath,
} from "./package-release.mjs";
import { sha256 } from "./checksum-release.mjs";

describe("release packaging", () => {
  it("creates a deterministic archive independent of input order", () => {
    const entries = [
      { name: "index.html", data: Buffer.from("<p>ok</p>") },
      { name: "assets/app.js", data: Buffer.from("export {};") },
    ];
    expect(sha256(createDeterministicZip(entries))).toBe(
      sha256(createDeterministicZip([...entries].reverse())),
    );
  });

  it.each(["../secret", "/absolute", "C:/absolute", "a\\b", "a/./b", ""])(
    "rejects unsafe path %j",
    (candidate) => {
      expect(() => safeArchivePath(candidate)).toThrow();
    },
  );

  it("rejects duplicate paths, source maps and credential-like entries", () => {
    expect(() =>
      createDeterministicZip([
        { name: "index.html", data: Buffer.from("one") },
        { name: "index.html", data: Buffer.from("two") },
      ]),
    ).toThrow("Duplicate release path");
    expect(() =>
      createDeterministicZip([
        { name: "assets/app.js.map", data: Buffer.from("{}") },
      ]),
    ).toThrow("Source map");
    expect(() =>
      createDeterministicZip([{ name: ".env", data: Buffer.from("TOKEN=x") }]),
    ).toThrow("Credential-like");
  });

  it("requires an explicit force flag for exact-version replacement", () => {
    expect(parseReleaseArguments([])).toEqual({ force: false });
    expect(parseReleaseArguments(["--force"])).toEqual({ force: true });
    expect(() => parseReleaseArguments(["--unknown"])).toThrow(
      "Unknown release argument",
    );
  });
});
