const fs = require('fs');
const path = require('path');

const serverModulesPath = path.join(__dirname, '../apps/server/src/modules');

// 模块迁移映射
const migrations = {
  user: [
    { from: 'auth/auth.controller.ts', to: 'user/auth/auth.controller.ts', oldPrefix: 'auth', newPrefix: 'api/user/auth' },
    { from: 'auth/auth.service.ts', to: 'user/auth/auth.service.ts' },
    { from: 'auth/auth.module.ts', to: 'user/auth/auth.module.ts' },
    { from: 'auth/dto', to: 'user/auth/dto', isDir: true },

    { from: 'user/user-user.controller.ts', to: 'user/profile/profile.controller.ts', oldPrefix: 'user', newPrefix: 'api/user/profile' },
    { from: 'user/user.service.ts', to: 'user/profile/profile.service.ts' },

    { from: 'guest/guest.controller.ts', to: 'user/guest/guest.controller.ts', oldPrefix: 'user/guests', newPrefix: 'api/user/guests' },
    { from: 'guest/guest.service.ts', to: 'user/guest/guest.service.ts' },
    { from: 'guest/guest.module.ts', to: 'user/guest/guest.module.ts' },
    { from: 'guest/dto', to: 'user/guest/dto', isDir: true },

    { from: 'order/order-user.controller.ts', to: 'user/order/order.controller.ts', oldPrefix: 'orders', newPrefix: 'api/user/orders' },

    { from: 'review/review-user.controller.ts', to: 'user/review/review.controller.ts', oldPrefix: 'reviews', newPrefix: 'api/user/reviews' },

    { from: 'coupon/coupon-user.controller.ts', to: 'user/coupon/coupon.controller.ts', oldPrefix: 'user/coupons', newPrefix: 'api/user/coupons' },

    { from: 'finance/finance-user.controller.ts', to: 'user/finance/finance.controller.ts', oldPrefix: 'user/finance', newPrefix: 'api/user/finance' },
    { from: 'finance/withdrawal-user.controller.ts', to: 'user/finance/withdrawal.controller.ts', oldPrefix: 'user/finance/withdrawals', newPrefix: 'api/user/finance/withdrawals' },

    { from: 'activity/activity-user.controller.ts', to: 'user/activity/activity.controller.ts', oldPrefix: 'user/activity/invite', newPrefix: 'api/user/activity/invite' },
  ],

  merchant: [
    { from: 'seller-auth/seller-auth.controller.ts', to: 'merchant/auth/auth.controller.ts', oldPrefix: 'seller/auth', newPrefix: 'api/merchant/auth' },
    { from: 'seller-auth/seller-auth.service.ts', to: 'merchant/auth/auth.service.ts' },
    { from: 'seller-auth/seller-auth.module.ts', to: 'merchant/auth/auth.module.ts' },
    { from: 'seller-auth/dto', to: 'merchant/auth/dto', isDir: true },

    { from: 'merchant/merchant-seller.controller.ts', to: 'merchant/profile/profile.controller.ts', oldPrefix: 'seller/merchant', newPrefix: 'api/merchant/profile' },
    { from: 'merchant/statistics-seller.controller.ts', to: 'merchant/statistics/statistics.controller.ts', oldPrefix: 'seller/statistics', newPrefix: 'api/merchant/statistics' },

    { from: 'room/room-seller.controller.ts', to: 'merchant/room/room.controller.ts', oldPrefix: 'seller/rooms', newPrefix: 'api/merchant/rooms' },

    { from: 'room-calendar/room-calendar.controller.ts', to: 'merchant/room-calendar/room-calendar.controller.ts', oldPrefix: 'seller/room-calendar', newPrefix: 'api/merchant/room-calendar' },
    { from: 'room-calendar/room-calendar.service.ts', to: 'merchant/room-calendar/room-calendar.service.ts' },
    { from: 'room-calendar/room-calendar.module.ts', to: 'merchant/room-calendar/room-calendar.module.ts' },
    { from: 'room-calendar/dto', to: 'merchant/room-calendar/dto', isDir: true },

    { from: 'order/order-seller.controller.ts', to: 'merchant/order/order.controller.ts', oldPrefix: 'seller/orders', newPrefix: 'api/merchant/orders' },

    { from: 'review/review-seller.controller.ts', to: 'merchant/review/review.controller.ts', oldPrefix: 'seller/reviews', newPrefix: 'api/merchant/reviews' },

    { from: 'finance/transaction-seller.controller.ts', to: 'merchant/finance/transaction.controller.ts', oldPrefix: 'merchant/finance/transactions', newPrefix: 'api/merchant/finance/transactions' },
    { from: 'finance/withdrawal-merchant.controller.ts', to: 'merchant/finance/withdrawal.controller.ts', oldPrefix: 'merchant/finance/withdrawals', newPrefix: 'api/merchant/finance/withdrawals' },
    { from: 'finance/settlement-merchant.controller.ts', to: 'merchant/finance/settlement.controller.ts', oldPrefix: 'merchant/finance/settlements', newPrefix: 'api/merchant/finance/settlements' },
  ],

  admin: [
    { from: 'admin-auth/admin-auth.controller.ts', to: 'admin/auth/auth.controller.ts', oldPrefix: 'admin/auth', newPrefix: 'api/admin/auth' },
    { from: 'admin-auth/admin-auth.service.ts', to: 'admin/auth/auth.service.ts' },
    { from: 'admin-auth/admin-auth.module.ts', to: 'admin/auth/auth.module.ts' },
    { from: 'admin-auth/dto', to: 'admin/auth/dto', isDir: true },

    { from: 'user/user-admin.controller.ts', to: 'admin/user/user.controller.ts', oldPrefix: 'admin/users', newPrefix: 'api/admin/users' },

    { from: 'merchant/merchant-admin.controller.ts', to: 'admin/merchant/merchant.controller.ts', oldPrefix: 'admin/merchants', newPrefix: 'api/admin/merchants' },

    { from: 'room/room-admin.controller.ts', to: 'admin/room/room.controller.ts', oldPrefix: 'admin/rooms', newPrefix: 'api/admin/rooms' },

    { from: 'order/order-admin.controller.ts', to: 'admin/order/order.controller.ts', oldPrefix: 'admin/orders', newPrefix: 'api/admin/orders' },

    { from: 'review/review-admin.controller.ts', to: 'admin/review/review.controller.ts', oldPrefix: 'admin/reviews', newPrefix: 'api/admin/reviews' },

    { from: 'coupon/coupon-admin.controller.ts', to: 'admin/coupon/coupon.controller.ts', oldPrefix: 'admin/coupons', newPrefix: 'api/admin/coupons' },

    { from: 'activity/activity-admin.controller.ts', to: 'admin/activity/activity.controller.ts', oldPrefix: 'admin/activity', newPrefix: 'api/admin/activity' },

    { from: 'config/config.controller.ts', to: 'admin/config/config.controller.ts', oldPrefix: 'admin/config', newPrefix: 'api/admin/config' },
    { from: 'config/config.service.ts', to: 'admin/config/config.service.ts' },
    { from: 'config/config.module.ts', to: 'admin/config/config.module.ts' },
    { from: 'config/dto', to: 'admin/config/dto', isDir: true },

    { from: 'finance/account-admin.controller.ts', to: 'admin/finance/account.controller.ts', oldPrefix: 'admin/finance/accounts', newPrefix: 'api/admin/finance/accounts' },
    { from: 'finance/transaction-admin.controller.ts', to: 'admin/finance/transaction.controller.ts', oldPrefix: 'admin/finance/transactions', newPrefix: 'api/admin/finance/transactions' },
    { from: 'finance/withdrawal-admin.controller.ts', to: 'admin/finance/withdrawal.controller.ts', oldPrefix: 'admin/finance/withdrawals', newPrefix: 'api/admin/finance/withdrawals' },
    { from: 'finance/settlement-admin.controller.ts', to: 'admin/finance/settlement.controller.ts', oldPrefix: 'admin/finance/settlements', newPrefix: 'api/admin/finance/settlements' },
    { from: 'finance/reconciliation-admin.controller.ts', to: 'admin/finance/reconciliation.controller.ts', oldPrefix: 'admin/finance/reconciliations', newPrefix: 'api/admin/finance/reconciliations' },
    { from: 'finance/report-admin.controller.ts', to: 'admin/finance/report.controller.ts', oldPrefix: 'admin/finance/reports', newPrefix: 'api/admin/finance/reports' },
  ],

  shared: [
    { from: 'room/room-public.controller.ts', to: 'shared/room/room.controller.ts', oldPrefix: 'rooms', newPrefix: 'api/public/rooms' },

    { from: 'merchant/merchant-public.controller.ts', to: 'shared/merchant/merchant.controller.ts', oldPrefix: 'merchants', newPrefix: 'api/public/merchants' },

    { from: 'activity/activity-public.controller.ts', to: 'shared/activity/activity.controller.ts', oldPrefix: 'activity', newPrefix: 'api/public/activity' },

    { from: 'upload/upload.controller.ts', to: 'shared/upload/upload.controller.ts',
      replacements: [
        { old: "@Controller('upload')", new: "@Controller('api/user/upload')" },
        { old: "@Controller('seller/upload')", new: "@Controller('api/merchant/upload')" },
        { old: "@Controller('admin/upload')", new: "@Controller('api/admin/upload')" },
      ]
    },
    { from: 'upload/upload.service.ts', to: 'shared/upload/upload.service.ts' },
    { from: 'upload/upload.module.ts', to: 'shared/upload/upload.module.ts' },
  ],
};

// 复制并修改文件
function copyAndModifyFile(fromPath, toPath, modifications) {
  const fullFromPath = path.join(serverModulesPath, fromPath);
  const fullToPath = path.join(serverModulesPath, toPath);

  if (!fs.existsSync(fullFromPath)) {
    console.log(`⚠️  源文件不存在: ${fromPath}`);
    return;
  }

  // 确保目标目录存在
  const toDir = path.dirname(fullToPath);
  if (!fs.existsSync(toDir)) {
    fs.mkdirSync(toDir, { recursive: true });
  }

  // 读取文件内容
  let content = fs.readFileSync(fullFromPath, 'utf8');

  // 应用修改
  if (modifications) {
    if (modifications.oldPrefix && modifications.newPrefix) {
      // 替换 @Controller 装饰器中的路由前缀
      content = content.replace(
        new RegExp(`@Controller\\(['"]${modifications.oldPrefix.replace(/\//g, '\\/')}['"]\\)`, 'g'),
        `@Controller('${modifications.newPrefix}')`
      );
    }

    if (modifications.replacements) {
      modifications.replacements.forEach(({ old, new: newStr }) => {
        content = content.replace(new RegExp(old.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'), 'g'), newStr);
      });
    }
  }

  // 写入新文件
  fs.writeFileSync(fullToPath, content, 'utf8');
  console.log(`✅ 已复制: ${fromPath} -> ${toPath}`);
}

// 复制目录
function copyDirectory(fromPath, toPath) {
  const fullFromPath = path.join(serverModulesPath, fromPath);
  const fullToPath = path.join(serverModulesPath, toPath);

  if (!fs.existsSync(fullFromPath)) {
    console.log(`⚠️  源目录不存在: ${fromPath}`);
    return;
  }

  if (!fs.existsSync(fullToPath)) {
    fs.mkdirSync(fullToPath, { recursive: true });
  }

  const files = fs.readdirSync(fullFromPath);
  files.forEach(file => {
    const fromFile = path.join(fullFromPath, file);
    const toFile = path.join(fullToPath, file);

    if (fs.statSync(fromFile).isDirectory()) {
      copyDirectory(path.join(fromPath, file), path.join(toPath, file));
    } else {
      fs.copyFileSync(fromFile, toFile);
    }
  });

  console.log(`✅ 已复制目录: ${fromPath} -> ${toPath}`);
}

// 执行迁移
console.log('🚀 开始模块重构...\n');

Object.entries(migrations).forEach(([category, items]) => {
  console.log(`\n📦 处理 ${category} 模块:`);
  items.forEach(item => {
    if (item.isDir) {
      copyDirectory(item.from, item.to);
    } else {
      copyAndModifyFile(item.from, item.to, {
        oldPrefix: item.oldPrefix,
        newPrefix: item.newPrefix,
        replacements: item.replacements
      });
    }
  });
});

console.log('\n✨ 模块重构完成！');
console.log('\n⚠️  注意：');
console.log('1. 需要手动创建各端的总模块文件（user.module.ts, merchant.module.ts, admin.module.ts等）');
console.log('2. 需要更新 app.module.ts 注册新模块');
console.log('3. 需要更新前端 API 调用路径');
console.log('4. Service 和 Module 文件可能需要手动调整导入路径');
