const { pool } = require('./src/config/database');
const jwt = require('jsonwebtoken');
const config = require('./src/config/config');
const User = require('./src/models/User');

(async () => {
  try {
    console.log('=== Testing Server Response ===');
    
    // Test simple GET request first
    console.log('Testing GET /api/departments...');
    const getResponse = await fetch('http://localhost:3000/api/departments');
    console.log('GET Response status:', getResponse.status);
    
    if (getResponse.ok) {
      const data = await getResponse.json();
      console.log('GET Success! Departments count:', data.data?.departments?.length || 0);
    } else {
      const errorText = await getResponse.text();
      console.error('GET Error response:', errorText);
    }
    
    // Now test POST with authentication
    console.log('\n=== Testing POST with Authentication ===');
    
    // Get Super Admin user
    const [users] = await pool.execute('SELECT id FROM users WHERE email = ?', ['s_admin@gmail.com']);
    const userId = users[0].id;
    const user = await User.findById(userId);
    
    // Create JWT token
    const token = jwt.sign(
      { 
        id: user.id, 
        email: user.email,
        role: user.role,
        role_id: user.role_id
      },
      config.jwt.secret,
      { expiresIn: config.jwt.expiresIn }
    );
    
    const departmentData = {
      name: 'Test Department',
      unit_id: 1,
      description: 'Test description'
    };
    
    const postResponse = await fetch('http://localhost:3000/api/departments', {
      method: 'POST',
      headers: {
        'Authorization': `Bearer ${token}`,
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(departmentData)
    });
    
    console.log('POST Response status:', postResponse.status);
    
    if (!postResponse.ok) {
      const errorText = await postResponse.text();
      console.error('POST Error response:', errorText);
    } else {
      const data = await postResponse.json();
      console.log('POST Success! Data:', data);
    }
    
    process.exit(0);
  } catch (error) {
    console.error('Error:', error);
    process.exit(1);
  }
})();



