const mysql = require('mysql2/promise');
require('dotenv').config();

async function testOrderAssignment() {
  const connection = await mysql.createConnection({
    host: process.env.DB_HOST || 'localhost',
    user: process.env.DB_USER || 'root',
    password: process.env.DB_PASSWORD || '',
    database: process.env.DB_NAME || 'tuc'
  });

  try {
    console.log('🔍 Testing order assignment setup...\n');
    
    // Check users with Master role
    const [masters] = await connection.execute(`
      SELECT id, name, email, role 
      FROM users 
      WHERE role = 'Master' AND isDeleted = 0
    `);
    
    console.log('👑 Master users:');
    masters.forEach(master => {
      console.log(`  ID: ${master.id}, Name: ${master.name}, Email: ${master.email}`);
    });

    // Check orders table structure
    const [orderColumns] = await connection.execute(`
      DESCRIBE orders
    `);
    
    console.log('\n📋 Orders table structure:');
    orderColumns.forEach(col => {
      console.log(`  ${col.Field}: ${col.Type} ${col.Null === 'NO' ? 'NOT NULL' : 'NULL'} ${col.Default ? `DEFAULT ${col.Default}` : ''}`);
    });

    // Check existing orders
    const [orders] = await connection.execute(`
      SELECT id, schoolId, masterId, name, type, status, totalQuantity, isDeleted 
      FROM orders 
      WHERE isDeleted = 0 
      LIMIT 5
    `);
    
    console.log(`\n📦 Found ${orders.length} active orders:`);
    orders.forEach(order => {
      console.log(`  ID: ${order.id}, School: ${order.schoolId}, Master: ${order.masterId}`);
      console.log(`      Name: ${order.name}, Type: ${order.type}, Status: ${order.status}`);
      console.log(`      Quantity: ${order.totalQuantity}\n`);
    });

    console.log('✅ Order assignment test completed successfully!');
    console.log('\n📋 Summary:');
    console.log(`   - ${masters.length} Master users found`);
    console.log(`   - ${orders.length} orders found`);
    console.log('   - Orders table has masterId and status columns');
    
  } catch (error) {
    console.error('❌ Test failed:', error.message);
    throw error;
  } finally {
    await connection.end();
  }
}

// Run the test
if (require.main === module) {
  testOrderAssignment()
    .then(() => {
      console.log('\nTest script completed');
      process.exit(0);
    })
    .catch((error) => {
      console.error('Test script failed:', error);
      process.exit(1);
    });
}

module.exports = testOrderAssignment;