/**
 * 添加物流公司联系人表迁移脚本
 * 修复物流公司详情获取失败的问题
 * 日期：2026-04-08
 */

const db = require('../db-sqlite');

async function createLogisticsCompanyContactsTable() {
  try {
    console.log('开始创建物流公司联系人表...');
    
    // 创建物流公司联系人表
    await db.query(`
      CREATE TABLE IF NOT EXISTS logistics_company_contacts (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        logistics_company_id INTEGER NOT NULL,
        name TEXT NOT NULL,
        phone TEXT,
        email TEXT,
        position TEXT,
        is_primary INTEGER DEFAULT 0,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        FOREIGN KEY (logistics_company_id) REFERENCES logistics_companies(id) ON DELETE CASCADE
      )
    `);
    
    // 创建索引
    await db.query('CREATE INDEX IF NOT EXISTS idx_lc_contacts_company ON logistics_company_contacts(logistics_company_id)');
    await db.query('CREATE INDEX IF NOT EXISTS idx_lc_contacts_primary ON logistics_company_contacts(is_primary)');
    
    console.log('物流公司联系人表创建成功！');
    
    // 检查是否有现有的物流公司，为它们添加默认联系人
    const companies = await db.query('SELECT id, name FROM logistics_companies');
    
    if (companies.rows.length > 0) {
      console.log(`为 ${companies.rows.length} 个物流公司添加默认联系人...`);
      
      for (const company of companies.rows) {
        // 检查是否已有联系人
        const existingContacts = await db.query(
          'SELECT COUNT(*) as count FROM logistics_company_contacts WHERE logistics_company_id = ?',
          [company.id]
        );
        
        if (existingContacts.rows[0].count === 0) {
          // 添加默认联系人
          await db.query(`
            INSERT INTO logistics_company_contacts 
            (logistics_company_id, name, phone, email, position, is_primary, created_at)
            VALUES (?, ?, ?, ?, ?, 1, datetime('now'))
          `, [company.id, '默认联系人', '', '', '联系人']);
          
          console.log(`为物流公司 "${company.name}" 添加了默认联系人`);
        }
      }
    }
    
    console.log('迁移完成！');
    return { success: true, message: '物流公司联系人表创建成功' };
  } catch (error) {
    console.error('创建物流公司联系人表失败:', error);
    return { success: false, message: '创建物流公司联系人表失败', error: error.message };
  }
}

// 如果直接运行此脚本
if (require.main === module) {
  createLogisticsCompanyContactsTable()
    .then(result => {
      if (result.success) {
        console.log('✅ 迁移成功:', result.message);
        process.exit(0);
      } else {
        console.error('❌ 迁移失败:', result.message);
        process.exit(1);
      }
    })
    .catch(error => {
      console.error('❌ 迁移执行失败:', error);
      process.exit(1);
    });
}

module.exports = createLogisticsCompanyContactsTable;