const { pool } = require('./src/config/database');

(async () => {
  try {
    console.log('🔧 Seeding group_contact_mappings from active users...');

    // Detect an organization to seed (prefer 1)
    const [orgRows] = await pool.execute('SELECT id, name FROM organizations ORDER BY id ASC LIMIT 1');
    if (!orgRows.length) {
      console.log('❌ No organizations found. Aborting.');
      process.exit(1);
    }
    const organizationId = orgRows[0].id;
    console.log(`✅ Using organization_id=${organizationId} (${orgRows[0].name})`);

    // Pick some active users to map (limit to 50 to avoid over-seeding)
    const [userRows] = await pool.execute(
      'SELECT id FROM users WHERE is_active = 1 AND organization_id = ? ORDER BY id ASC LIMIT 50',
      [organizationId]
    );

    if (!userRows.length) {
      console.log('❌ No active users found to map. Aborting.');
      process.exit(1);
    }

    // Build mappings (org-level: department_id NULL)
    const mappings = userRows.map(u => [organizationId, null, u.id]);

    const [result] = await pool.query(
      'INSERT IGNORE INTO group_contact_mappings (organization_id, department_id, contact_id) VALUES ?',
      [mappings]
    );

    console.log('📊 Seed result:', {
      attempted: mappings.length,
      inserted: result.affectedRows,
      skipped: mappings.length - result.affectedRows
    });

    // Show a quick count
    const [countRows] = await pool.execute('SELECT COUNT(*) AS c FROM group_contact_mappings WHERE organization_id = ?', [organizationId]);
    console.log(`✅ Total mappings for org ${organizationId}:`, countRows[0].c);

    console.log('✅ Seeding completed.');
  } catch (err) {
    console.error('❌ Error during seeding:', err.message);
    process.exit(1);
  } finally {
    try { await pool.end(); } catch {}
  }
})();


