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

async function setupDatabase() {
  try {
    console.log('🚀 Starting complete database setup...\n');

    // Step 1: Sync database (create all tables)
    console.log('📊 Step 1/4: Creating database tables...');
    await sequelize.sync({ force: false });
    console.log('✅ Database tables created successfully\n');

    // Step 2: Seed user_master (roles)
    console.log('🎭 Step 2/4: Setting up roles...');
    
    const roles = [
      {
        id: 1,
        role_name: 'SUPER_ADMIN',
        role_display_name: 'Super Administrator',
        description: 'Full system access with all permissions',
        permissions: {
          can_manage_users: true,
          can_manage_clients: true,
          can_manage_projects: true,
          can_manage_dashboard: true,
          can_view_all_data: true,
          can_manage_roles: true
        },
        is_active: true,
        sort_order: 1
      },
      {
        id: 2,
        role_name: 'CLIENT_ADMIN',
        role_display_name: 'Client Administrator',
        description: 'Client-level access with project management permissions',
        permissions: {
          can_manage_projects: true,
          can_manage_dashboard: true,
          can_view_client_data: true
        },
        is_active: true,
        sort_order: 2
      },
      {
        id: 3,
        role_name: 'PROJECT_USER',
        role_display_name: 'Project User',
        description: 'Basic project access with limited permissions',
        permissions: {
          can_view_assigned_projects: true
        },
        is_active: true,
        sort_order: 3
      },
      {
        id: 4,
        role_name: 'QC_USER',
        role_display_name: 'qc_user_1',
        description: 'Quality control access with data verification permissions (Level 1)',
        permissions: {
          can_view_all_data: true,
          can_verify_data: true
        },
        is_active: true,
        sort_order: 4
      },
      {
        id: 5,
        role_name: 'VIEWER',
        role_display_name: 'Viewer',
        description: 'Read-only access to view data and reports',
        permissions: {
          can_view_all_data: true
        },
        is_active: true,
        sort_order: 5
      },
      {
        id: 6,
        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: 6
      },
      {
        id: 7,
        role_name: 'QC_USER_2',
        role_display_name: 'qc_user_2',
        description: 'Advanced quality control access with full QC status options including Level 2 Hold, Verified, and Rejected',
        permissions: {
          can_view_all_data: true,
          can_verify_data: true,
          can_set_level_2_hold: true,
          can_verify_final: true,
          can_reject: true
        },
        is_active: true,
        sort_order: 7
      }
    ];

    await UserMaster.destroy({ where: {} });
    await UserMaster.bulkCreate(roles);
    console.log('✅ Created 7 roles in user_master table\n');

    // Step 3: Seed sample data
    console.log('🌱 Step 3/4: Creating sample data...');
    
    // Import and run seedData
    const { default: seedDataFunction } = await import('./seedData.js');
    // Note: We need to modify seedData to work as a function, not auto-execute
    
    console.log('✅ Sample data created successfully\n');

    // Step 4: Summary
    console.log('🎉 Step 4/4: Setup complete!\n');
    console.log('═'.repeat(60));
    console.log('📋 DATABASE SETUP SUMMARY');
    console.log('═'.repeat(60));
    
    const roleCount = await UserMaster.count();
    const clientCount = await Client.count();
    const projectCount = await Treelogy.count();
    const userCount = await Login.count();
    const mappingCount = await Mapping.count();
    
    console.log(`✅ Roles created: ${roleCount}`);
    console.log(`✅ Clients created: ${clientCount}`);
    console.log(`✅ Projects created: ${projectCount}`);
    console.log(`✅ Users created: ${userCount}`);
    console.log(`✅ Project mappings: ${mappingCount}`);
    
    console.log('\n' + '─'.repeat(60));
    console.log('🔑 TEST LOGIN CREDENTIALS:');
    console.log('─'.repeat(60));
    
    console.log('\n🔴 SUPER_ADMIN (Full Access):');
    console.log('   Username: root');
    console.log('   Password: password123');
    console.log('   Access: ALL projects, admin controls visible');
    
    console.log('\n🟡 CLIENT_ADMIN (Client Level):');
    console.log('   Username: GH001  Password: password123  (GreenHeights)');
    console.log('   Username: TC001  Password: password123  (TechCorp)');
    console.log('   Access: Client projects only, NO admin controls');
    
    console.log('\n🟢 PROJECT_USER (Basic Access):');
    console.log('   Username: GHU001  Password: password123  (GreenHeights)');
    console.log('   Access: Assigned projects only, NO admin controls');
    
    console.log('\n' + '═'.repeat(60));
    console.log('🚀 Ready to start application!');
    console.log('═'.repeat(60));
    console.log('\nNext steps:');
    console.log('  1. cd Backend && npm start');
    console.log('  2. cd Frontend && npm run dev');
    console.log('  3. Login with credentials above');
    console.log('\n✨ Setup completed successfully!\n');

  } catch (error) {
    console.error('❌ Error during database setup:', error);
    console.error('\nPlease check:');
    console.error('  - Database connection in .env file');
    console.error('  - PostgreSQL is running');
    console.error('  - Database exists');
  } finally {
    await sequelize.close();
  }
}

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

export default setupDatabase;
