import { readFile } from "node:fs/promises";

import {
  findMissingOperations,
  loadJsonSource,
} from "./openapi-contract.mjs";

const source = process.argv[2] ?? process.env.BACKEND_OPENAPI_SOURCE;
if (!source) {
  throw new Error(
    "Provide an OpenAPI JSON path/URL or set BACKEND_OPENAPI_SOURCE",
  );
}

const contractUrl = new URL(
  "../../src/data/services/api/api_contract.json",
  import.meta.url,
);
const [contract, openApiDocument] = await Promise.all([
  readFile(contractUrl, "utf8").then(JSON.parse),
  loadJsonSource(source),
]);
const missing = findMissingOperations(contract, openApiDocument);

if (missing.length > 0) {
  const details = missing
    .map(
      ({ operationId, method, path, reason }) =>
        `- ${operationId}: ${method.toUpperCase()} ${path} (${reason})`,
    )
    .join("\n");
  throw new Error(`Backend OpenAPI is missing frontend operations:\n${details}`);
}

console.log(
  `Backend OpenAPI covers all ${Object.keys(contract).length} frontend operations.`,
);
