/**
 * @file Tests for GET/DELETE /api/lanes/:id/proof… and POST
 * /api/lanes/:id/proof-link — the HTTP surface over server/lib/proof.js.
 * @author Nguyễn Ngọc Trí Vĩ <vinnt@smartgift.vn>
 */

const os = require("node:os");
const path = require("node:path");
const fs = require("node:fs");
const http = require("node:http");

const SUITE_ROOT = fs.mkdtempSync(path.join(os.tmpdir(), "ccam-proof-api-"));
process.env.DASHBOARD_DB_PATH = path.join(SUITE_ROOT, "dashboard.db");
process.env.LANES_ROOT = path.join(SUITE_ROOT, "lanes");

const { describe, it, before, after } = require("node:test");
const assert = require("node:assert/strict");

const { createApp } = require("../index");
const lanesLib = require("../lib/lanes");

let server;
let PORT;

before(async () => {
  const app = createApp();
  server = http.createServer(app);
  await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve));
  PORT = server.address().port;
});
after(async () => {
  await new Promise((resolve) => server.close(resolve));
  fs.rmSync(SUITE_ROOT, { recursive: true, force: true });
});

function request(method, urlPath, body) {
  return new Promise((resolve, reject) => {
    const data = body ? JSON.stringify(body) : null;
    const req = http.request(
      {
        method,
        hostname: "127.0.0.1",
        port: PORT,
        path: urlPath,
        headers: {
          "Content-Type": "application/json",
          ...(data ? { "Content-Length": Buffer.byteLength(data) } : {}),
        },
      },
      (res) => {
        let raw = "";
        res.on("data", (chunk) => (raw += chunk));
        res.on("end", () => {
          let json = null;
          try {
            json = JSON.parse(raw);
          } catch {
            /* binary body (image) is fine */
          }
          resolve({ status: res.statusCode, headers: res.headers, body: json, raw });
        });
      }
    );
    req.on("error", reject);
    if (data) req.write(data);
    req.end();
  });
}

let laneSeq = 0;
function makeLane() {
  laneSeq += 1;
  const cwd = path.join(SUITE_ROOT, `lane-cwd-${laneSeq}`);
  fs.mkdirSync(cwd, { recursive: true });
  return lanesLib.createLane({ title: `lane ${laneSeq}`, cwd, kind: "managed" });
}

function writeShot(lane, slug, group, name) {
  const dir = path.join(lane.cwd, ".playwright-mcp", "proof", slug, group);
  fs.mkdirSync(dir, { recursive: true });
  fs.writeFileSync(path.join(dir, name), "fake-png-bytes");
}

describe("GET /api/lanes/:id/proof", () => {
  it("lists grouped screenshots", async () => {
    const lane = makeLane();
    writeShot(lane, "one", "qc-local", "a.png");
    const res = await request("GET", `/api/lanes/${lane.id}/proof`);
    assert.equal(res.status, 200);
    const one = res.body.features.find((f) => f.slug === "one");
    assert.deepEqual(one.groups["qc-local"], ["a.png"]);
  });
});

describe("GET /api/lanes/:id/proof/:slug/:group/:file", () => {
  it("serves an existing screenshot", async () => {
    const lane = makeLane();
    writeShot(lane, "one", "qc-local", "a.png");
    const res = await request("GET", `/api/lanes/${lane.id}/proof/one/qc-local/a.png`);
    assert.equal(res.status, 200);
    assert.equal(res.raw, "fake-png-bytes");
  });

  it("404s a traversal attempt", async () => {
    const lane = makeLane();
    writeShot(lane, "one", "qc-local", "a.png");
    const res = await request(
      "GET",
      `/api/lanes/${lane.id}/proof/one/qc-local/${encodeURIComponent("../../../etc/passwd")}`
    );
    assert.equal(res.status, 404);
  });
});

describe("DELETE /api/lanes/:id/proof/:slug", () => {
  it("deletes listed images", async () => {
    const lane = makeLane();
    writeShot(lane, "one", "qc-local", "a.png");
    const res = await request("DELETE", `/api/lanes/${lane.id}/proof/one`, {
      group: "qc-local",
      images: ["a.png"],
    });
    assert.equal(res.status, 200);
    assert.equal(res.body.deleted, 1);
  });

  it("400s EBADPATH for a slug containing ..", async () => {
    const lane = makeLane();
    const res = await request(
      "DELETE",
      `/api/lanes/${lane.id}/proof/${encodeURIComponent("../escape")}`,
      {}
    );
    assert.equal(res.status, 400);
    assert.equal(res.body.error.code, "EBADPATH");
  });

  it("404s ENOFEATURE for a slug with no proof dir", async () => {
    const lane = makeLane();
    const res = await request("DELETE", `/api/lanes/${lane.id}/proof/never-had-proof`, {});
    assert.equal(res.status, 404);
    assert.equal(res.body.error.code, "ENOFEATURE");
  });
});

describe("POST /api/lanes/:id/proof-link", () => {
  it("creates the symlink and reports linked: true", async () => {
    const lane = makeLane();
    const res = await request("POST", `/api/lanes/${lane.id}/proof-link`);
    assert.equal(res.status, 200);
    assert.equal(res.body.linked, true);
    assert.equal(fs.lstatSync(path.join(lane.cwd, "proof")).isSymbolicLink(), true);
  });
});
