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('=== Debugging Add New Department Permission Issue ===');
    
    // Get Super Admin user
    const [users] = await pool.execute('SELECT id FROM users WHERE email = ?', ['s_admin@gmail.com']);
    if (users.length === 0) {
      console.log('Super Admin user not found');
      process.exit(1);
    }
    
    const userId = users[0].id;
    const user = await User.findById(userId);
    
    console.log('Super Admin user:', {
      id: user.id,
      name: user.name,
      email: user.email,
      role: user.role,
      role_id: user.role_id
    });
    
    // 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 }
    );
    
    console.log('Generated token:', token.substring(0, 50) + '...');
    
    // Test department creation API
    console.log('\n=== Testing Department Creation API ===');
    
    const departmentData = {
      name: 'Test Department',
      unit_id: 1,
      description: 'Test description'
    };
    
    const response = await fetch('http://localhost:3000/api/departments', {
      method: 'POST',
      headers: {
        'Authorization': `Bearer ${token}`,
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(departmentData)
    });
    
    console.log('Response status:', response.status);
    console.log('Response headers:', Object.fromEntries(response.headers.entries()));
    
    if (!response.ok) {
      const errorText = await response.text();
      console.error('Error response:', errorText);
    } else {
      const data = await response.json();
      console.log('Success! Created department:', data);
    }
    
    process.exit(0);
  } catch (error) {
    console.error('Error:', error);
    process.exit(1);
  }
})();



