import http from "node:http";

const port = Number(process.env.QJCLAW_CLOUD_API_PORT || 4318);
const token = process.env.QJCLAW_SMOKE_AUTH_TOKEN || "smoke-token";

function sendJson(res, status, payload) {
  res.writeHead(status, { "Content-Type": "application/json; charset=utf-8" });
  res.end(JSON.stringify(payload));
}

function readAuth(req) {
  const header = req.headers.authorization || "";
  return header.startsWith("Bearer ") ? header.slice("Bearer ".length) : "";
}

const server = http.createServer((req, res) => {
  const url = new URL(req.url || "/", `http://127.0.0.1:${port}`);
  if (readAuth(req) !== token) {
    sendJson(res, 401, { message: "Invalid cloud access token." });
    return;
  }

  if (req.method === "GET" && url.pathname === "/v1/auth/session") {
    sendJson(res, 200, {
      user: { displayName: "Smoke User", email: "smoke.user@qianjiangclaw.local" },
      organization: { name: "Smoke Org" },
      expiresAt: new Date(Date.now() + 1000 * 60 * 60).toISOString()
    });
    return;
  }

  if (req.method === "GET" && url.pathname === "/v1/me/profile") {
    sendJson(res, 200, {
      id: "user-smoke",
      displayName: "Smoke User",
      email: "smoke.user@qianjiangclaw.local",
      organizationName: "Smoke Org",
      title: "Installer MVP Tester"
    });
    return;
  }

  if (req.method === "GET" && url.pathname === "/v1/me/credits") {
    sendJson(res, 200, {
      balance: 88,
      granted: 120,
      used: 32,
      updatedAt: new Date().toISOString(),
      expiresAt: new Date(Date.now() + 1000 * 60 * 60 * 24 * 14).toISOString()
    });
    return;
  }

  if (req.method === "GET" && url.pathname === "/v1/skills") {
    sendJson(res, 200, {
      items: [
        { id: "legal-research", name: "Legal Research", description: "Finds statutes and cases.", category: "research", enabled: true, requiresCredits: 4 },
        { id: "contract-review", name: "Contract Review", description: "Runs clause review workflows.", category: "analysis", enabled: true, requiresCredits: 10 }
      ]
    });
    return;
  }

  sendJson(res, 404, { message: `Unknown endpoint: ${req.method} ${url.pathname}` });
});

server.listen(port, "127.0.0.1", () => {
  process.stdout.write(`QJCLAW cloud API smoke server listening on http://127.0.0.1:${port}\n`);
});

for (const signal of ["SIGINT", "SIGTERM"]) {
  process.on(signal, () => {
    server.close(() => process.exit(0));
  });
}
