/**
 * 初始化管理员账号脚本
 * 运行: npx tsx src/scripts/init-admin.ts
 */
import 'reflect-metadata';
import bcrypt from 'bcryptjs';
import { initDatabase, AppDataSource, User, SystemConfig } from '../models/index.js';

async function initAdmin() {
  console.log('Initializing database...');
  
  try {
    await initDatabase();
    const dataSource = AppDataSource;
    
    const userRepo = dataSource.getRepository(User);
    const configRepo = dataSource.getRepository(SystemConfig);
    
    // 检查是否已存在 admin 用户
    const existingAdmin = await userRepo.findOne({ where: { username: 'admin' } });
    
    if (existingAdmin) {
      console.log('Admin user already exists, updating password...');
      existingAdmin.passwordHash = await bcrypt.hash('admin123', 10);
      await userRepo.save(existingAdmin);
      console.log('Admin password reset to: admin123');
    } else {
      console.log('Creating admin user...');
      const admin = userRepo.create({
        username: 'admin',
        email: 'admin@example.com',
        passwordHash: await bcrypt.hash('admin123', 10),
        nickname: '管理员',
        role: 'admin',
        status: 'active',
      });
      await userRepo.save(admin);
      console.log('Admin user created successfully!');
    }
    
    // 初始化系统配置
    const configs = [
      { configKey: 'allow_registration', configValue: 'true', description: '是否允许注册' },
      { configKey: 'default_role', configValue: 'operator', description: '默认用户角色' },
      { configKey: 'max_accounts_per_user', configValue: '10', description: '每用户最大账号数' },
      { configKey: 'max_tasks_per_day', configValue: '50', description: '每日最大任务数' },
    ];
    
    for (const cfg of configs) {
      const existing = await configRepo.findOne({ where: { configKey: cfg.configKey } });
      if (!existing) {
        await configRepo.save(configRepo.create(cfg));
        console.log(`Created config: ${cfg.configKey}`);
      }
    }
    
    console.log('\n✅ Initialization complete!');
    console.log('Login credentials:');
    console.log('  Username: admin');
    console.log('  Password: admin123');
    
    await dataSource.destroy();
    process.exit(0);
  } catch (error) {
    console.error('Initialization failed:', error);
    process.exit(1);
  }
}

initAdmin();
