const { PrismaClient } = require('@prisma/client');
const bcrypt = require('bcrypt');

console.log('👤 CRÉATION UTILISATEUR ADMIN\n');
console.log('='.repeat(50));

const prisma = new PrismaClient();

async function createAdmin() {
  try {
    console.log('🔍 Vérification des utilisateurs existants...');
    
    // Vérifier tous les utilisateurs existants
    const existingUsers = await prisma.user.findMany({
      select: {
        id: true,
        email: true,
        role: true,
        active: true
      },
      orderBy: { id: 'asc' }
    });

    console.log(`📋 ${existingUsers.length} utilisateurs trouvés:`);
    existingUsers.forEach(user => {
      console.log(`   ID: ${user.id}, Email: ${user.email}, Role: ${user.role}, Active: ${user.active}`);
    });

    // Chercher un admin actif
    const activeAdmin = existingUsers.find(u => u.role === 'admin' && u.active);
    
    if (activeAdmin) {
      console.log('\n✅ ADMIN ACTIF TROUVÉ:');
      console.log(`   ID: ${activeAdmin.id}`);
      console.log(`   Email: ${activeAdmin.email}`);
      return activeAdmin;
    }

    console.log('\n❌ Aucun admin actif trouvé, création...');

    // Créer un nouvel admin
    const hashedPassword = await bcrypt.hash('Admin123!', 10);
    
    const newAdmin = await prisma.user.create({
      data: {
        email: 'admin@ccis-agadir.com',
        password: hashedPassword,
        role: 'admin',
        active: true,
        permissions: ['Services', 'Users', 'Companies', 'WP'],
        member: {
          create: {
            firstName: 'Admin',
            lastName: 'System',
            phone: '+212600000000',
            active: true
          }
        }
      },
      include: {
        member: true
      }
    });

    console.log('🎉 NOUVEL ADMIN CRÉÉ:');
    console.log(`   ID: ${newAdmin.id}`);
    console.log(`   Email: ${newAdmin.email}`);
    console.log(`   Role: ${newAdmin.role}`);
    console.log(`   Permissions: ${newAdmin.permissions}`);
    
    return newAdmin;

  } catch (error) {
    console.log('❌ ERREUR:', error.message);
    if (error.code === 'P2002') {
      console.log('💡 L\'email existe déjà, utilisation de l\'utilisateur existant');
    }
  } finally {
    await prisma.$disconnect();
  }
}

createAdmin().catch(console.error);
