const { existsSync } = require('fs');
const { mkdirSync } = require('fs-extra');
const { join } = require('path');
const openApiConfig = require('../../config/config');
const { generateService } = require('./index');

function createMiddleware(config) {
  const cwd = process.cwd();
  return {
    middleware(req, res, next) {
      (async () => {
        const openAPIConfig = config;
        // const pageConfig = require(join(cwd, 'package.json'));
        const mockFolder = openAPIConfig.mock ? join(cwd, 'mock') : undefined;
        const serversFolder = join(cwd, 'src', 'api/generateAPI');
        // 如果mock 文件不存在，创建一下
        if (mockFolder && !existsSync(mockFolder)) {
          mkdirSync(mockFolder);
        }
        // 如果mock 文件不存在，创建一下
        if (serversFolder && !existsSync(serversFolder)) {
          mkdirSync(serversFolder);
        }
        // pageConfig.name.split('/').pop(),
        await generateService({
          projectName: '',
          ...openAPIConfig,
          serversPath: serversFolder,
          mockFolder,
        });
        console.log('[openAPI]: execution complete');
      })();
    },
  };
}

function openAPIMiddewares(req, res, next) {
  const { middleware } = createMiddleware(openApiConfig.openAPI);
  return middleware(req, res, next);
}
openAPIMiddewares();
