const mysql = require('mysql2/promise');
const path = require('path');
const fs = require('fs');

// 数据库配置（从.env读取或使用默认值）
const config = {
  host: process.env.DB_HOST || '129.211.213.226',
  port: process.env.DB_PORT || 9527,
  user: process.env.DB_USER || 'root',
  password: process.env.DB_PASSWORD || 'aiotAiot123!',
  database: process.env.DB_NAME || 'ningxia_zhengfu',
  multipleStatements: true // 允许执行多条SQL语句
};

async function run() {
  let connection;
  try {
    // 1. 连接数据库
    connection = await mysql.createConnection(config);
    console.log('数据库连接成功');

    // 2. 执行建表SQL
    const schemaSql = fs.readFileSync(
      path.join(__dirname, '../sql/schema.sql'), 
      'utf8'
    );
    await connection.query(schemaSql);
    console.log('数据库表创建完成');

    // 3. 插入测试数据
    const dataSql = fs.readFileSync(
      path.join(__dirname, '../sql/seed-data.sql'), 
      'utf8'
    );
    await connection.query(dataSql);
    console.log('测试数据插入完成');

    // 4. 验证数据
    const [entities] = await connection.query('SELECT COUNT(*) as count FROM supervision_entities');
    const [inspections] = await connection.query('SELECT COUNT(*) as count FROM inspections');
    console.log('\n数据验证结果:');
    console.log(`监管实体数量: ${entities[0].count}`);
    console.log(`检查记录数量: ${inspections[0].count}`);

  } catch (err) {
    console.error('数据库操作失败:', err.message);
  } finally {
    if (connection) {
      await connection.end();
      console.log('数据库连接已关闭');
    }
  }
}

// 立即执行
run();