/**
 * Create Super Admin User - Simple Version
 * Usage: node scripts/create-admin-simple.mjs
 */

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

const prisma = new PrismaClient();

const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout,
});

function question(prompt) {
  return new Promise((resolve) => {
    rl.question(prompt, resolve);
  });
}

async function createSuperAdmin() {
  console.log('\n🔐 Mawidi Super Admin Setup\n');

  try {
    // Get input
    const name = await question('Enter full name: ');
    const email = await question('Enter email: ');
    const username = await question('Enter username: ');
    const password = await question('Enter password (min 12 characters): ');

    // Validate
    if (!name || !email || !username || !password) {
      console.error('❌ All fields are required');
      rl.close();
      await prisma.$disconnect();
      process.exit(1);
    }

    if (password.length < 12) {
      console.error('❌ Password must be at least 12 characters');
      rl.close();
      await prisma.$disconnect();
      process.exit(1);
    }

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

    if (existing) {
      console.error('❌ Username or email already exists');
      rl.close();
      await prisma.$disconnect();
      process.exit(1);
    }

    // Hash password
    console.log('\n🔄 Creating account...');
    const hashedPassword = await bcrypt.hash(password, 12);

    // Create super admin
    const superAdmin = await prisma.users.create({
      data: {
        name,
        email,
        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, email },
      },
    });

    console.log('\n✅ Super admin created successfully!\n');
    console.log('📋 Account Details:');
    console.log(`   Name: ${name}`);
    console.log(`   Email: ${email}`);
    console.log(`   Username: ${username}`);
    console.log(`   Role: SUPER_ADMIN`);
    console.log(`\n🔗 Login at: http://localhost:9000/staff/login\n`);
  } catch (error) {
    console.error('❌ Failed to create super admin:', error.message);
  } finally {
    rl.close();
    await prisma.$disconnect();
    process.exit(0);
  }
}

createSuperAdmin();
