// 数据库模型同步脚本
const sequelize = require('../config/database');
const Farmer = require('../models/Farmer');

// 同步数据库模型并添加测试数据
async function syncAndSeed() {
  try {
    // 同步模型到数据库
    await sequelize.sync({ alter: true });
    console.log('数据库模型同步成功');
    
    // 检查是否已存在测试数据
    const existingCount = await Farmer.count();
    
    if (existingCount === 0) {
      // 添加测试数据
      const testFarmers = [
        {
          account: 'farmer001',
          nickname: '牛场小王',
          real_name: '王小明',
          farm_name: '明辉养殖场',
          farm_type: '规模',
          animal_type: '牛',
          animal_count: 200,
          address: '内蒙古自治区通辽市科尔沁区',
          registrar: 'admin',
          status: 'active'
        },
        {
          account: 'farmer002',
          nickname: '草原小李',
          real_name: '李草原',
          farm_name: '草原牧业',
          farm_type: '规模',
          animal_type: '羊',
          animal_count: 500,
          address: '内蒙古自治区通辽市开鲁县',
          registrar: 'admin',
          status: 'active'
        },
        {
          account: 'farmer003',
          nickname: '家庭养殖户老张',
          real_name: '张家庭',
          farm_name: '张记养殖场',
          farm_type: '散养',
          animal_type: '猪',
          animal_count: 50,
          address: '内蒙古自治区通辽市扎鲁特旗',
          registrar: 'admin',
          status: 'active'
        },
        {
          account: 'farmer004',
          nickname: '家禽养殖',
          real_name: '刘家禽',
          farm_name: '刘家养殖场',
          farm_type: '规模',
          animal_type: '鸡',
          animal_count: 2000,
          address: '内蒙古自治区通辽市霍林郭勒市',
          registrar: 'admin',
          status: 'active'
        },
        {
          account: 'farmer005',
          nickname: '特种养殖',
          real_name: '赵特种',
          farm_name: '特种养殖场',
          farm_type: '其他',
          animal_type: '其他',
          animal_count: 100,
          address: '内蒙古自治区通辽市库伦旗',
          registrar: 'admin',
          status: 'inactive'
        }
      ];
      
      await Farmer.bulkCreate(testFarmers);
      console.log('测试数据添加成功');
    } else {
      console.log('已存在测试数据，跳过添加');
    }
    
    // 关闭数据库连接
    await sequelize.close();
  } catch (error) {
    console.error('同步数据库模型或添加测试数据失败:', error);
    // 确保即使出错也关闭连接
    await sequelize.close();
  }
}

syncAndSeed();