"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.generate = generate;
const path_1 = __importDefault(require("path"));
const fs_extra_1 = __importDefault(require("fs-extra"));
const inquirer_1 = __importDefault(require("inquirer"));
const chalk_1 = __importDefault(require("chalk"));
const logger_1 = require("../utils/logger");
const GENERATOR_TYPES = {
    s: 'service',
    service: 'service',
    u: 'util',
    util: 'util',
    i: 'interceptor',
    interceptor: 'interceptor',
    uts: 'uts-job',
    'uts-job': 'uts-job',
    m: 'model',
    model: 'model',
};
const TYPE_TARGETS = {
    service: 'src/services',
    util: 'src/utils',
    interceptor: 'src/interceptor',
    'uts-job': 'src/uts',
    model: 'src/model',
};
async function generate(type, name, options) {
    (0, logger_1.printBanner)();
    // 1. 验证类型
    const generatorType = GENERATOR_TYPES[type.toLowerCase()];
    if (!generatorType) {
        logger_1.logger.error(`不支持的类型: ${type}`);
        console.log('支持的类型:');
        console.log('  service (s)   - 微服务');
        console.log('  util (u)      - 工具类');
        console.log('  interceptor (i) - 拦截器');
        console.log('  uts-job (uts) - 定时任务');
        console.log('  model (m)     - 数据模型');
        process.exit(1);
    }
    // 2. 检查当前目录是否是项目根目录
    const packageJsonPath = path_1.default.resolve(process.cwd(), 'package.json');
    if (!fs_extra_1.default.existsSync(packageJsonPath)) {
        logger_1.logger.error('请在项目根目录下执行此命令');
        process.exit(1);
    }
    // 3. 收集额外信息
    const answers = await promptGeneratorDetails(generatorType, name);
    // 4. 生成文件
    const targetDir = path_1.default.resolve(process.cwd(), TYPE_TARGETS[generatorType]);
    const fileName = `${name}.ts`;
    const filePath = path_1.default.join(targetDir, fileName);
    // 检查文件是否已存在
    if (fs_extra_1.default.existsSync(filePath)) {
        logger_1.logger.error(`文件已存在: ${filePath}`);
        process.exit(1);
    }
    // 生成代码
    const code = generateCode(generatorType, name, answers);
    // 确保目标目录存在
    await fs_extra_1.default.ensureDir(targetDir);
    // 写入文件
    await fs_extra_1.default.writeFile(filePath, code, 'utf-8');
    logger_1.logger.success(`已创建: ${filePath}`);
    // 5. 自动注册（如果需要）
    if (options.register) {
        await registerToProject(generatorType, name, answers);
    }
    logger_1.logger.newline();
    logger_1.logger.success(chalk_1.default.green('代码生成完成!'));
}
async function promptGeneratorDetails(type, name) {
    const questions = [];
    switch (type) {
        case 'service':
            questions.push({
                type: 'input',
                name: 'sid',
                message: '请输入服务ID (sid):',
                default: `cn.example.project.${name}`,
            }, {
                type: 'list',
                name: 'method',
                message: '请求方式:',
                choices: ['ALL', 'GET', 'POST'],
                default: 'ALL',
            }, {
                type: 'confirm',
                name: 'requireAuth',
                message: '是否需要登录验证?',
                default: true,
            });
            break;
        case 'interceptor':
            questions.push({
                type: 'input',
                name: 'description',
                message: '拦截器描述:',
                default: `${name} 拦截器`,
            });
            break;
        case 'uts-job':
            questions.push({
                type: 'input',
                name: 'cron',
                message: 'Cron 表达式:',
                default: '0 0 * * * *',
            }, {
                type: 'input',
                name: 'description',
                message: '任务描述:',
                default: `${name} 定时任务`,
            });
            break;
        case 'util':
        case 'model':
            questions.push({
                type: 'input',
                name: 'description',
                message: '描述:',
                default: '',
            });
            break;
    }
    return inquirer_1.default.prompt(questions);
}
function generateCode(type, name, answers) {
    switch (type) {
        case 'service':
            return generateServiceCode(name, answers);
        case 'util':
            return generateUtilCode(name, answers);
        case 'interceptor':
            return generateInterceptorCode(name, answers);
        case 'uts-job':
            return generateUtsJobCode(name, answers);
        case 'model':
            return generateModelCode(name, answers);
        default:
            return '';
    }
}
function generateServiceCode(name, answers) {
    return `import { IService } from 'mslib';
import { logger, OpResult } from 'mslib';

/**
 * ${name} 服务
 * sid: ${answers.sid}
 */
export class ${name} implements IService {

    async doService(params: any): Promise<OpResult> {
        // TODO: 实现业务逻辑
        logger.info('${name} doService called, params:', params);

        return OpResult.success({
            message: 'Hello from ${name}'
        });
    }
}
`;
}
function generateUtilCode(name, answers) {
    const desc = answers.description ? ` - ${answers.description}` : '';
    return `/**
 * ${name} 工具类${desc}
 */
export class ${name} {

    /**
     * 示例方法
     */
    static example(): void {
        // TODO: 实现功能
    }
}
`;
}
function generateInterceptorCode(name, answers) {
    return `import { HandlerInterceptor } from './HandlerInterceptor';
import { logger } from 'mslib';

/**
 * ${answers.description}
 */
export class ${name} implements HandlerInterceptor {

    async preService(request: any, reply: any): Promise<boolean> {
        // TODO: 实现拦截逻辑
        logger.info('${name} interceptor called');

        // 返回 true 继续执行，返回 false 终止请求
        return true;
    }
}
`;
}
function generateUtsJobCode(name, answers) {
    return `import { UTSJob } from './UTSJob';
import { logger } from 'mslib';

/**
 * ${answers.description}
 * Cron: ${answers.cron}
 */
export class ${name} implements UTSJob {

    /**
     * 获取 cron 表达式
     */
    getCron(): string {
        return '${answers.cron}';
    }

    /**
     * 执行任务
     */
    async execute(): Promise<void> {
        logger.info('${name} executing at', new Date().toISOString());

        // TODO: 实现任务逻辑

        logger.info('${name} completed');
    }
}
`;
}
function generateModelCode(name, answers) {
    const desc = answers.description ? ` - ${answers.description}` : '';
    return `/**
 * ${name} 数据模型${desc}
 */
export interface ${name} {
    id?: string;
    createdAt?: Date;
    updatedAt?: Date;
    // TODO: 添加更多字段
}
`;
}
async function registerToProject(type, name, answers) {
    if (type === 'service') {
        // 注册到 ServiceRouters.ts
        const routerPath = path_1.default.resolve(process.cwd(), 'src/routers/ServiceRouters.ts');
        if (fs_extra_1.default.existsSync(routerPath)) {
            let content = await fs_extra_1.default.readFile(routerPath, 'utf-8');
            // 添加导入
            const importLine = `import { ${name} } from '../services/${name}';`;
            if (!content.includes(importLine)) {
                // 找到占位符
                const placeholder = '//下面這個requires是个占位符，不可删除';
                if (content.includes(placeholder)) {
                    content = content.replace(placeholder, `${placeholder}\n${importLine}`);
                }
                // 注册路由
                const dispatchPlaceholder = '//下面這個dispach是个占位符，不可删除';
                const dispatchLine = `this.routers.set('${answers.sid}', new ${name}());`;
                if (content.includes(dispatchPlaceholder)) {
                    content = content.replace(dispatchPlaceholder, `${dispatchPlaceholder}\n        ${dispatchLine}`);
                }
                await fs_extra_1.default.writeFile(routerPath, content, 'utf-8');
                logger_1.logger.success(`已注册到 ServiceRouters.ts`);
            }
        }
    }
}
//# sourceMappingURL=generate.js.map