import { readFileSync, rmSync } from "node:fs";
import { sep, resolve } from "node:path";

import { generateClient } from "./lib/generate-client.mjs";
import {
  buildApiContracts,
  compareTrees,
  createOpenApiDocument,
  formattedJson,
} from "./lib/openapi.mjs";

buildApiContracts();
const document = await createOpenApiDocument();
const expectedDocument = readFileSync("openapi/openapi.json", "utf8");
const currentDocument = formattedJson(document);

const buildRoot = resolve(".build");
const generatedRoot = resolve(buildRoot, "openapi-client-check");
if (!generatedRoot.startsWith(`${buildRoot}${sep}`)) throw new Error("Generated check path escaped .build.");
rmSync(generatedRoot, { force: true, recursive: true });
await generateClient(resolve("openapi/openapi.json"), generatedRoot);

const clientDiff = compareTrees(resolve("apps/web/src/generated/api"), generatedRoot);
const result = {
  client_diff: clientDiff,
  openapi: document.openapi,
  snapshot_match: currentDocument === expectedDocument,
  status: currentDocument === expectedDocument && clientDiff.length === 0 ? "passed" : "failed",
};
console.log(JSON.stringify(result, null, 2));
if (result.status !== "passed") process.exit(1);
