import sequelize from './config/config.js';
import { UserMaster } from './models/index.js';

async function testRolesAPI() {
  try {
    console.log('🧪 Testing Roles API...\n');

    // Fetch all active roles
    const roles = await UserMaster.findAll({
      where: { is_active: true },
      order: [['sort_order', 'ASC']],
      attributes: ['id', 'role_name', 'role_display_name', 'description', 'permissions', 'sort_order']
    });

    console.log(`✅ Found ${roles.length} active roles:\n`);
    
    roles.forEach((role, index) => {
      console.log(`${index + 1}. ${role.role_display_name} (${role.role_name})`);
      console.log(`   ID: ${role.id}`);
      console.log(`   Sort Order: ${role.sort_order}`);
      console.log(`   Description: ${role.description}`);
      console.log(`   Permissions:`, JSON.stringify(role.permissions, null, 2));
      console.log('');
    });

    // Check specifically for SURVEYOR role
    const surveyorRole = roles.find(r => r.role_name === 'SURVEYOR');
    if (surveyorRole) {
      console.log('✅ SURVEYOR role is present and active!');
      console.log(`   Will be available for: SUPER_ADMIN, CLIENT_ADMIN\n`);
    } else {
      console.log('❌ SURVEYOR role not found!\n');
    }

    console.log('🎉 Test completed successfully!\n');

  } catch (error) {
    console.error('❌ Error testing roles API:', error);
  } finally {
    await sequelize.close();
  }
}

// Run if called directly
if (import.meta.url === `file://${process.argv[1]}`) {
  testRolesAPI();
}

export default testRolesAPI;

