/**
 * Unauthenticated write endpoints on the legacy /api surface.
 *
 * POST /api/repos had no auth middleware at all and took the target namespace
 * from `owner` in the request body — anyone on the internet could create a
 * repository inside any user's namespace. csrfProtect does not mitigate it:
 * src/middleware/csrf.ts explicitly returns next() for paths under /api/.
 *
 * POST /api/setup was likewise open and upserts a user, seeding any username
 * that does not yet exist with the fixed password "changeme" — anonymous
 * account creation and username squatting on a populated instance.
 */

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

async function postJson(path: string, body: unknown, headers: Record<string, string> = {}) {
  return app.fetch(
    new Request(`http://localhost${path}`, {
      method: "POST",
      headers: { "content-type": "application/json", ...headers },
      body: JSON.stringify(body),
    })
  );
}

describe("POST /api/repos requires authentication", () => {
  it("rejects an anonymous caller with 401, not 400/500", async () => {
    const res = await postJson("/api/repos", {
      name: "pwned",
      owner: "someoneelse",
    });
    expect(res.status).toBe(401);
    const body = await res.json();
    expect(body.error).toBe("Authentication required");
  });

  it("rejects before parsing the body, so a malformed body still 401s", async () => {
    // Auth must be the first gate — otherwise the shape of the error leaks
    // whether the endpoint would have accepted the request.
    const res = await app.fetch(
      new Request("http://localhost/api/repos", {
        method: "POST",
        headers: { "content-type": "application/json" },
        body: "{not json",
      })
    );
    expect(res.status).toBe(401);
  });

  it("an invalid bearer token does not pass as authenticated", async () => {
    const res = await postJson(
      "/api/repos",
      { name: "pwned" },
      { authorization: "Bearer glc_deadbeefdeadbeefdeadbeefdeadbeef" }
    );
    expect(res.status).toBe(401);
  });
});

describe("POST /api/setup is first-run only", () => {
  it("404s on an instance that already has users", async () => {
    const res = await postJson("/api/setup", {
      username: "squatter",
      email: "a@b.c",
      repoName: "x",
    });
    // 404 (not 403) so a live instance does not advertise the endpoint.
    // 503 is acceptable here: no DATABASE_URL in the unit-test environment
    // means the user-count probe cannot run, and it must not fall through.
    expect([404, 503]).toContain(res.status);
    expect(res.status).not.toBe(200);
  });
});

describe("the namespace check itself", () => {
  const SRC = readFileSync("src/routes/api.ts", "utf8");
  const handler = SRC.slice(
    SRC.indexOf('api.post("/repos"'),
    SRC.indexOf('api.get("/repos")') > 0
      ? SRC.indexOf('api.get("/repos")')
      : SRC.indexOf('api.get("/users/:username/repos"')
  );

  it("forces the owner to the authenticated user", () => {
    expect(handler).toContain("body.owner = viewer.username");
  });

  it("refuses a mismatched owner rather than silently rewriting it", () => {
    // Silently rewriting would make a forged request look like it succeeded
    // against the attacker's own namespace.
    expect(handler).toContain("body.owner !== viewer.username");
    expect(handler).toContain("403");
  });
});

