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

async function addSurveyorRole() {
  try {
    console.log('🚀 Adding SURVEYOR role to database...\n');

    // Check if SURVEYOR role already exists
    const existingRole = await UserMaster.findOne({ where: { role_name: 'SURVEYOR' } });
    
    if (existingRole) {
      console.log('✅ SURVEYOR role already exists!');
      console.log('   ID:', existingRole.id);
      console.log('   Display Name:', existingRole.role_display_name);
      return;
    }

    // Fix the sequence for user_master table
    console.log('🔧 Fixing user_master ID sequence...');
    await sequelize.query(`
      SELECT setval(
        pg_get_serial_sequence('user_master', 'id'),
        (SELECT COALESCE(MAX(id), 0) + 1 FROM user_master),
        false
      );
    `);
    console.log('✅ Sequence fixed\n');

    // Get the highest existing sort_order
    const maxSortOrder = await UserMaster.max('sort_order') || 0;
    
    // Create SURVEYOR role (let database auto-generate ID)
    const surveyorRole = await UserMaster.create({
      role_name: 'SURVEYOR',
      role_display_name: 'Surveyor',
      description: 'Field surveyor with data collection and entry permissions',
      permissions: {
        can_collect_data: true,
        can_enter_tree_details: true,
        can_view_assigned_projects: true
      },
      is_active: true,
      sort_order: maxSortOrder + 1
    });

    console.log('✅ SURVEYOR role created successfully!');
    console.log('   ID:', surveyorRole.id);
    console.log('   Display Name:', surveyorRole.role_display_name);
    console.log('   Permissions:', JSON.stringify(surveyorRole.permissions, null, 2));
    
    console.log('\n🎉 Migration completed successfully!\n');

  } catch (error) {
    console.error('❌ Error adding SURVEYOR role:', error);
    console.error('\nPlease check:');
    console.error('  - Database connection in .env file');
    console.error('  - PostgreSQL is running');
    console.error('  - user_master table exists');
  } finally {
    await sequelize.close();
  }
}

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

export default addSurveyorRole;

