import fs from "fs";
import os from "os";
import path from "path";
import { afterEach, describe, expect, it } from "vitest";
import { sanitizeSnapshotFile } from "./template-steps.mjs";

const tempDirs = [];

afterEach(() => {
  while (tempDirs.length > 0) {
    fs.rmSync(tempDirs.pop(), { recursive: true, force: true });
  }
});

function makeTempDir(prefix) {
  const dir = fs.mkdtempSync(path.join(os.tmpdir(), prefix));
  tempDirs.push(dir);
  return dir;
}

describe("template snapshot sanitization", () => {
  it("removes volatile pg_dump control lines", () => {
    const dir = makeTempDir("testkit-template-snapshot-");
    const filePath = path.join(dir, "schema.sql");
    fs.writeFileSync(
      filePath,
      [
        "SET statement_timeout = 0;",
        "SET transaction_timeout = 0;",
        "\\restrict abc123",
        "CREATE TABLE public.widgets (id integer);",
        "\\unrestrict abc123",
        "",
      ].join("\n")
    );

    sanitizeSnapshotFile(filePath);

    expect(fs.readFileSync(filePath, "utf8")).toBe(
      ["SET statement_timeout = 0;", "CREATE TABLE public.widgets (id integer);", ""].join("\n")
    );
  });
});
