/**
 * Regression coverage for the silent-empty-import bug: a `git clone --bare
 * --mirror` of an empty / unreachable / token-less-private source exits 0 yet
 * produces a repo with zero commits, which the importer used to register as a
 * successful import (DB row + "success"). A Vapron import "succeeded" this way
 * while transferring nothing — dangerous once the GitHub source is deleted.
 *
 * countRepoCommits() is the gate that makes an import trustworthy: it must
 * return 0 for an empty bare repo and > 0 once history exists.
 */
import { describe, it, expect, beforeAll, afterAll } from "bun:test";
import { mkdtempSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { countRepoCommits } from "../lib/import-helper";

function git(cwd: string, ...args: string[]) {
  const p = Bun.spawnSync(["git", ...args], { cwd, stdout: "pipe", stderr: "pipe" });
  if (p.exitCode !== 0) {
    throw new Error(`git ${args.join(" ")} failed: ${new TextDecoder().decode(p.stderr)}`);
  }
}

let root = "";
beforeAll(() => {
  root = mkdtempSync(join(tmpdir(), "import-empty-guard-"));
});
afterAll(() => {
  if (root) rmSync(root, { recursive: true, force: true });
});

describe("countRepoCommits — the import empty-guard", () => {
  it("returns 0 for a freshly-init'd EMPTY bare repo (the phantom-import case)", async () => {
    const empty = join(root, "empty.git");
    git(root, "init", "--bare", empty);
    expect(await countRepoCommits(empty)).toBe(0);
  });

  it("returns 0 for a path that isn't a git repo at all", async () => {
    expect(await countRepoCommits(join(root, "does-not-exist"))).toBe(0);
  });

  it("returns > 0 once the repo actually has history", async () => {
    // Build a work repo with one commit, then mirror-clone it bare (exactly
    // what the importer does) and confirm the guard sees the history.
    const work = join(root, "work");
    git(root, "init", "-b", "main", work);
    git(work, "config", "user.email", "t@t.com");
    git(work, "config", "user.name", "t");
    Bun.spawnSync(["git", "-C", work, "commit", "--allow-empty", "-m", "seed"], { stdout: "pipe", stderr: "pipe" });

    const mirror = join(root, "mirror.git");
    git(root, "clone", "--bare", "--mirror", work, mirror);
    expect(await countRepoCommits(mirror)).toBeGreaterThan(0);
  });
});
