/**
 * Malformed URL ids must 404, not 500.
 *
 * Handlers passed raw path segments into database predicates.
 * `parseInt("abc", 10)` is NaN, and NaN or a malformed UUID makes Postgres
 * raise, which the global error handler turns into a 500. Live, before the
 * fix: /:owner/:repo/issues/abc returned 500 while
 * /:owner/:repo/issues/99999999 correctly returned 404 — so a typo or a stale
 * link produced a server error rather than "not found".
 *
 * Found by the authz-matrix gate, which probes every repo-scoped route with a
 * placeholder id; eight routes answered 5xx.
 */

import { describe, expect, it } from "bun:test";
import { parseIdNumber, parseIdUuid } from "../lib/route-params";

describe("parseIdNumber", () => {
  it("accepts a positive integer", () => {
    expect(parseIdNumber("1")).toBe(1);
    expect(parseIdNumber("42")).toBe(42);
    expect(parseIdNumber("99999999")).toBe(99999999);
  });

  for (const bad of ["abc", "", "0", "-1", "1.5", " 1", "1 ", "NaN", "Infinity"]) {
    it(`rejects ${JSON.stringify(bad)}`, () => {
      expect(parseIdNumber(bad)).toBeNull();
    });
  }

  it("rejects numeric-prefixed junk that parseInt would truncate", () => {
    // parseInt("12abc", 10) === 12, which would silently load the wrong row.
    expect(parseIdNumber("12abc")).toBeNull();
  });

  it("rejects undefined", () => {
    expect(parseIdNumber(undefined)).toBeNull();
  });

  it("rejects values beyond safe integer range", () => {
    expect(parseIdNumber("999999999999999999999")).toBeNull();
  });
});

describe("parseIdUuid", () => {
  it("accepts a well-formed uuid in either case", () => {
    const u = "df1c027c-a830-4c42-aafc-b3bc7155477c";
    expect(parseIdUuid(u)).toBe(u);
    expect(parseIdUuid(u.toUpperCase())).toBe(u.toUpperCase());
  });

  for (const bad of [
    "abc",
    "",
    "df1c027c-a830-4c42-aafc",
    "df1c027c_a830_4c42_aafc_b3bc7155477c",
    "zzzzzzzz-a830-4c42-aafc-b3bc7155477c",
    "df1c027c-a830-4c42-aafc-b3bc7155477cc",
  ]) {
    it(`rejects ${JSON.stringify(bad)}`, () => {
      expect(parseIdUuid(bad)).toBeNull();
    });
  }
});

describe("the sentinel flows into existing not-found paths", () => {
  it("callers use `?? -1`, which matches no row", () => {
    // Deliberate: -1 can never equal a real issue/PR number, so each handler
    // falls through the not-found branch it already had. No new branches, no
    // behaviour change for valid input.
    const { readFileSync } = require("fs") as typeof import("fs");
    const issues = readFileSync("src/routes/issues.tsx", "utf8");
    expect(issues).toContain("parseIdNumber(c.req.param(\"number\")) ?? -1");
    expect(issues).not.toMatch(/parseInt\(c\.req\.param\("number"\), 10\)/);
  });

  it("no route still parses a number param with bare parseInt", () => {
    const { readdirSync, readFileSync, statSync } = require("fs") as typeof import("fs");
    const { join } = require("path") as typeof import("path");
    const walk = (d: string): string[] =>
      readdirSync(d).flatMap((e) => {
        const p = join(d, e);
        return statSync(p).isDirectory() ? walk(p) : [p];
      });
    const offenders: string[] = [];
    for (const f of walk("src/routes")) {
      if (!/\.tsx?$/.test(f)) continue;
      const src = readFileSync(f, "utf8");
      if (/parseInt\(c\.req\.param\("(number|prNumber|issueNumber)"\), 10\)/.test(src)) {
        offenders.push(f.replace(/\\/g, "/"));
      }
    }
    expect(offenders).toEqual([]);
  });
});
