import { validationMetadatasToSchemas } from '@odit/class-validator-jsonschema';
import consola from "consola";
import fs from "fs";
import "reflect-metadata";
import { createExpressServer, getMetadataArgsStorage } from "routing-controllers";
import { generateSpec } from '../src/apispec';
import { config } from '../src/config';
import authchecker from "../src/middlewares/authchecker";
import { ErrorHandler } from '../src/middlewares/ErrorHandler';

const CONTROLLERS_FILE_EXTENSION = process.env.NODE_ENV === 'production' ? 'js' : 'ts';
createExpressServer({
    authorizationChecker: authchecker,
    middlewares: [ErrorHandler],
    development: config.development,
    cors: true,
    routePrefix: "/api",
    controllers: [`${__dirname}/../src/controllers/*.${CONTROLLERS_FILE_EXTENSION}`],
});

const storage = getMetadataArgsStorage();
const schemas = validationMetadatasToSchemas({
    refPointerPrefix: "#/components/schemas/",
});

//Spec creation based on the previously created schemas
const spec = generateSpec(storage, schemas);

try {
    fs.writeFileSync("./openapi.json", JSON.stringify(spec), { encoding: "utf-8" });
    consola.success("Exported openapi spec to openapi.json");
} catch (error) {
    consola.error("Couldn't export the openapi spec");
}
