/**
 requestLibPath
 schemaPath
 mock
 projectName
 */

const node_fetch = require('node-fetch');
const swagger2openapi = require('swagger2openapi');
const serviceGenerators = require('./serviceGenerator');
const mockGenerator = require('./mockGenerator');
const log = require('./log');
const getImportStatement = (requestLibPath) => {
    if (requestLibPath && requestLibPath.startsWith('import')) {
        return requestLibPath;
    }
    if (requestLibPath) {
        return `import request from '${requestLibPath}'`;
    }
    return `import { request } from "umi"`;
}

const converterSwaggerToOpenApi = (swagger) => {
    if (!swagger.swagger) {
        return swagger;
    }
    return new Promise((resolve, reject) => {
        swagger2openapi.convertObj(swagger, {}, (err, options) => {
            log(['💺 将 Swagger 转化为 openAPI']);
            if (err) {
                reject(err);
                return;
            }
            resolve(options.openapi);
        });
    });
};

const getSchema = async (schemaPath) => {
    if (schemaPath.startsWith('http')) {
        const json = await node_fetch(schemaPath).then((rest) => rest.json());
        return json;
    }
    const schema = require(schemaPath);
    return schema;
};

const getOpenAPIConfig = async (schemaPath) => {
    const schema = await getSchema(schemaPath);
    const openAPI = await converterSwaggerToOpenApi(schema);
    if (!schema) {
        return null;
    }
    return openAPI;
};

// 从 appName 生成 service 数据
const generateService = async ({ requestLibPath, schemaPath, mockFolder, ...rest }) => {
    const openAPI = await getOpenAPIConfig(schemaPath);
    const requestImportStatement = getImportStatement(requestLibPath);
    const serviceGenerator = new serviceGenerators.ServiceGenerator({
        namespace: 'API',
        basePath: openAPI.servers[0].url,
        requestImportStatement,
        ...rest,
    }, openAPI);
    serviceGenerator.genFile();
    if (mockFolder) {
        await mockGenerator.mockGenerator({
            openAPI,
            mockFolder: mockFolder || './mocks/',
        });
    }
    process.exit();
};


module.exports = {
    generateService,
    getSchema
}
