import { openapiSchemaToJsonSchema } from '@openapi-contrib/openapi-schema-to-json-schema';
import { convertObj } from 'swagger2openapi';
import { generateRuntimeModule } from '../../utils/index.js';
export const apiPlugin = ({ localBasePath, }) => {
    return {
        name: 'doom-api',
        async addRuntimeModules(config, isProd) {
            return {
                'doom-@api-virtual': `export default ${JSON.stringify({ references: config.api?.references, pathPrefix: config.api?.pathPrefix }, null, isProd ? 0 : 2)}`,
                ...(await generateRuntimeModule(config.api?.crds, 'api-crds', config.root, localBasePath, isProd)),
                ...(await generateRuntimeModule(config.api?.openapis, 'api-openapis', config.root, localBasePath, isProd, async (doc) => {
                    // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
                    doc.info ??= { title: 'Unknown', version: '0.0.0' };
                    if ('swagger' in doc && doc.swagger === '2.0') {
                        doc = (await convertObj(doc, {})).openapi;
                    }
                    if ('openapi' in doc && doc.openapi.startsWith('3.0.')) {
                        doc = openapiSchemaToJsonSchema(doc);
                        doc.openapi = '3.1.0';
                    }
                    return doc;
                })),
            };
        },
    };
};
