/**
 * Forking must not publish a private repository.
 *
 * POST /:owner/:repo/fork was gated only by `requireAuth` plus `repoExists()`.
 * repoExists is a bare filesystem probe (Bun.file(<repoPath>/HEAD).exists())
 * that never reads the repositories row, so it never sees isPrivate — and the
 * insert hardcoded `isPrivate: false`. Any logged-in user could fork a private
 * repo they had no read access to, and the clone landed as a PUBLIC repo.
 * One POST turned someone else's private source public.
 */

import { describe, expect, it } from "bun:test";
import { readFileSync } from "fs";

const SRC = readFileSync("src/routes/fork.tsx", "utf8");
const handler = SRC.slice(SRC.indexOf('fork.post("/:owner/:repo/fork"'));

describe("fork access gate", () => {
  it("checks read access via resolveRepoAccess before cloning", () => {
    expect(handler).toContain("resolveRepoAccess");
    expect(handler).toContain('access === "none"');
  });

  it("gates BEFORE the git clone, not after", () => {
    const gate = handler.indexOf('access === "none"');
    const clone = handler.indexOf('"git", "clone"');
    expect(gate).toBeGreaterThan(-1);
    expect(clone).toBeGreaterThan(-1);
    // Cloning first would copy the private objects to disk even if the DB
    // insert were later refused.
    expect(gate).toBeLessThan(clone);
  });

  it("denies indistinguishably from a missing repo", () => {
    // Must not become an oracle for which private repos exist: the denial
    // path is the same redirect a non-existent repo takes.
    const denial = handler.slice(
      handler.indexOf('access === "none"'),
      handler.indexOf('"git", "clone"')
    );
    expect(denial).toContain("c.redirect(`/${ownerName}/${repoName}`)");
    expect(denial).not.toMatch(/403|Forbidden|not allowed/i);
  });
});

describe("fork visibility", () => {
  it("inherits the source repo's visibility instead of hardcoding public", () => {
    expect(handler).toContain("isPrivate: sourceRepo.isPrivate");
    // Match the code shape, not the prose: the phrase also appears in the
    // comment explaining what the old behaviour was.
    expect(handler).not.toMatch(/^\s*isPrivate: false,/m);
  });
});
