#!/usr/bin/env node

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

const prisma = new PrismaClient();

async function setupAdmin() {
  try {
    console.log('🔧 Setting up admin user for production...');

    // Generate secure credentials
    const username = 'eliza';
    const password = crypto.randomBytes(12).toString('base64').replace(/[+/=]/g, '').substring(0, 16);
    
    console.log('\n📋 Generated Credentials:');
    console.log('Username:', username);
    console.log('Password:', password);
    console.log('\n⚠️  IMPORTANT: Save these credentials securely!');

    // Hash the password
    const saltRounds = 12;
    const passwordHash = await bcrypt.hash(password, saltRounds);

    // Check if admin user already exists
    const existingAdmin = await prisma.adminUser.findUnique({
      where: { username }
    });

    if (existingAdmin) {
      // Update existing admin
      await prisma.adminUser.update({
        where: { username },
        data: {
          passwordHash,
          updatedAt: new Date()
        }
      });
      console.log('\n✅ Admin user updated successfully!');
    } else {
      // Create new admin user
      await prisma.adminUser.create({
        data: {
          username,
          passwordHash,
          createdAt: new Date(),
          updatedAt: new Date()
        }
      });
      console.log('\n✅ Admin user created successfully!');
    }

    console.log('\n🚀 Production setup complete!');
    console.log('Eliza can now log in with the credentials above.');

  } catch (error) {
    console.error('❌ Error setting up admin user:', error);
    process.exit(1);
  } finally {
    await prisma.$disconnect();
  }
}

// Run the setup
setupAdmin();
