import { Login, UserMaster, Mapping } from './models/index.js';
import bcrypt from 'bcryptjs';
import sequelize from './config/config.js';

/**
 * Helper script to create a QC_USER_2 account
 * Usage: node create_qc_user_2.js
 */

async function createQCUser2() {
  try {
    console.log('🚀 Creating QC_USER_2 account...\n');

    // Check if QC_USER_2 role exists
    const qcUser2Role = await UserMaster.findOne({
      where: { role_name: 'QC_USER_2' }
    });

    if (!qcUser2Role) {
      console.error('❌ QC_USER_2 role not found in database!');
      console.log('\nPlease run the migration script first:');
      console.log('  psql -U your_username -d your_database -f add_qc_user_2_role.sql');
      console.log('\nOr run the database setup:');
      console.log('  node setupDatabase.js');
      process.exit(1);
    }

    console.log('✅ QC_USER_2 role found');

    // Create QC_USER_2 account
    const username = 'QC002';
    const password = '12345';
    const hashedPassword = await bcrypt.hash(password, 10);

    // Check if user already exists
    const existingUser = await Login.findOne({
      where: { username }
    });

    if (existingUser) {
      console.log(`⚠️  User ${username} already exists. Updating role...`);
      await existingUser.update({
        role_id: qcUser2Role.id
      });
      console.log(`✅ Updated ${username} to QC_USER_2 role`);
    } else {
      const newUser = await Login.create({
        username,
        password: hashedPassword,
        name: 'QC User Level 2',
        role_id: qcUser2Role.id,
        client_id: null, // QC users typically don't belong to a specific client
        status: 'Y',
        is_mobile_user: 'N'
      });

      console.log(`✅ Created new user: ${username}`);
      console.log(`   Role: ${qcUser2Role.role_display_name}`);
      console.log(`   Password: ${password}`);
    }

    // Optional: Map to a project
    // Uncomment and modify the following if you want to map the user to specific projects
    /*
    const projectId = 1; // Change this to your project ID
    const existingMapping = await Mapping.findOne({
      where: {
        login_id: newUser.login_id,
        treelogy_id: projectId
      }
    });

    if (!existingMapping) {
      await Mapping.create({
        login_id: newUser.login_id,
        treelogy_id: projectId
      });
      console.log(`✅ Mapped user to project ${projectId}`);
    }
    */

    console.log('\n' + '═'.repeat(60));
    console.log('🎉 QC_USER_2 Account Created Successfully!');
    console.log('═'.repeat(60));
    console.log('\n📋 Login Credentials:');
    console.log(`   Username: ${username}`);
    console.log(`   Password: ${password}`);
    console.log(`   Role: Quality Control User Level 2`);
    console.log('\n🔐 Capabilities:');
    console.log('   ✅ View all dashboard data');
    console.log('   ✅ Access QC Dashboard');
    console.log('   ✅ Access Survey Inventory');
    console.log('   ✅ Set status: Unverified');
    console.log('   ✅ Set status: Level 1 Approved');
    console.log('   ✅ Set status: Level 2 Hold');
    console.log('   ✅ Set status: Verified');
    console.log('   ✅ Set status: Rejected');
    console.log('\n💡 Note: Assign this user to specific projects using the Project Mapping page');
    console.log('\n✨ Ready to login!\n');

  } catch (error) {
    console.error('❌ Error creating QC_USER_2:', error);
    console.error('\nPlease check:');
    console.error('  - Database connection is working');
    console.error('  - QC_USER_2 role exists in user_master table');
    console.error('  - Run migration script if needed');
  } finally {
    await sequelize.close();
  }
}

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

export default createQCUser2;

