/**
 * Create Asim's Super Admin Account
 */

import { PrismaClient } from '../lib/generated/prisma/index.js';
import bcrypt from 'bcryptjs';

const prisma = new PrismaClient();

async function createAsimAdmin() {
  console.log('\n🔐 Creating Asim\'s Super Admin Account...\n');

  try {
    const userData = {
      name: 'Asim',
      email: 'asim@mawidi.com',
      username: 'asim',
      password: 'AsimMawidi2025!',
    };

    // Check if already exists
    const existing = await prisma.users.findFirst({
      where: {
        OR: [
          { email: userData.email },
          { username: userData.username },
        ],
      },
    });

    if (existing) {
      console.log('ℹ️  Account already exists!');
      console.log(`   Username: ${existing.username || 'N/A'}`);
      console.log(`   Email: ${existing.email}`);
      console.log(`   Role: ${existing.role}`);

      if (existing.role !== 'SUPER_ADMIN') {
        console.log('\n🔄 Upgrading to SUPER_ADMIN...');
        await prisma.users.update({
          where: { id: existing.id },
          data: { role: 'SUPER_ADMIN' },
        });
        console.log('✅ Account upgraded to SUPER_ADMIN!');
      }

      console.log(`\n🔗 Login at: http://localhost:9000/staff/login`);
      console.log(`   Username: ${userData.username}`);
      console.log(`   Password: ${userData.password}\n`);

      await prisma.$disconnect();
      process.exit(0);
    }

    // Hash password
    console.log('🔄 Hashing password...');
    const hashedPassword = await bcrypt.hash(userData.password, 12);

    // Create super admin
    console.log('🔄 Creating account in database...');
    const superAdmin = await prisma.users.create({
      data: {
        name: userData.name,
        email: userData.email,
        username: userData.username,
        password: hashedPassword,
        role: 'SUPER_ADMIN',
        emailVerified: new Date(),
        isActive: true,
      },
    });

    // Log creation
    await prisma.audit_logs.create({
      data: {
        userId: superAdmin.id,
        type: 'super_admin_created',
        action: 'Super admin account created',
        success: true,
        ip: '127.0.0.1',
        metadata: {
          username: userData.username,
          email: userData.email,
        },
      },
    });

    console.log('\n✅ Super Admin Created Successfully!\n');
    console.log('📋 Account Details:');
    console.log(`   Name: ${userData.name}`);
    console.log(`   Email: ${userData.email}`);
    console.log(`   Username: ${userData.username}`);
    console.log(`   Password: ${userData.password}`);
    console.log(`   Role: SUPER_ADMIN`);
    console.log(`\n🔗 Login at: http://localhost:9000/staff/login\n`);
    console.log('💡 Save these credentials securely!\n');
  } catch (error) {
    console.error('❌ Failed to create super admin:');
    console.error(error.message);
    console.error('\nFull error:', error);
  } finally {
    await prisma.$disconnect();
    process.exit(0);
  }
}

createAsimAdmin();
