import { cosmiconfig } from "cosmiconfig";
import * as prettier from "prettier";
import { schema2typebox as Schema2Typebox } from "./schema-to-typebox";

export type Schema2TypeboxOptions = {
  /**
   * The given JSON schema as utf-8 encoded string.
   */
  input: string;
};

/**
 * Use this function for programmatic usage of schema2typebox. The options are
 * typed and commented.
 *
 * @returns The generated code as string
 *
 * @throws Error
 **/
export const schema2typebox = async ({
  input,
}: Schema2TypeboxOptions): Promise<string> => {
  const generatedTypeboxCode = await Schema2Typebox(input);

  // post-processing (formatting)
  const explorer = cosmiconfig("prettier");
  const prettierConfig = await explorer.search();
  const formattedResult = prettier.format(generatedTypeboxCode, {
    parser: "typescript",
    ...prettierConfig,
  });
  return addCommentThatCodeIsGenerated(formattedResult);
};

export const addCommentThatCodeIsGenerated = (code: string) => {
  return `/**
 * ATTENTION. This code was AUTO GENERATED by schema2typebox.
 * While I don't know your use case, there is a high chance that direct changes
 * to this file get lost. Consider making changes to the underlying JSON schema
 * you use to generate this file instead. The default file is called
 * "schema.json", perhaps have a look there! :]
 */

${code}`;
};
