import { writeFileSync } from "node:fs";
import {
  getIntrospectionQuery,
  GraphQLSchema,
  graphqlSync,
  lexicographicSortSchema,
  printSchema,
} from "graphql";
import { createPostGraphileSchema } from "postgraphile";
import pg from "pg";
import { loadConfig } from "@digiresilience/metamigo-config";
import { getPostGraphileOptions } from "@digiresilience/metamigo-db";

const { Pool } = pg;

export const exportGraphqlSchema = async (): Promise<void> => {
  const config = await loadConfig();

  const rootPgPool = new Pool({
    connectionString: config.db.connection,
  });
  const exportSchema = `../../data/schema.graphql`;
  const exportJson = `../../frontend/lib/graphql-schema.json`;
  try {
    const schema = (await createPostGraphileSchema(
      config.postgraphile.authConnection,
      "app_public",
      getPostGraphileOptions()
    )) as unknown as GraphQLSchema;
    const sorted = lexicographicSortSchema(schema);
    const json = graphqlSync({ schema, source: getIntrospectionQuery() });
    writeFileSync(exportSchema, printSchema(sorted));
    writeFileSync(exportJson, JSON.stringify(json));

    console.log(`GraphQL schema exported to ${exportSchema}`);
    console.log(`GraphQL schema json exported to ${exportJson}`);
  } finally {
    rootPgPool.end();
  }
};
