import { db } from '../config/database.js';
import { users } from '../db/schema.js';
import { eq } from 'drizzle-orm';
import { hashPassword } from '../utils/password.js';
import { logger } from '../utils/logger.js';

/**
 * Seed admin user
 *
 * Vytvorí admin používateľa s credentials:
 * - username: admin
 * - password: admin123
 *
 * ⚠️  DÔLEŽITÉ: Zmeňte heslo po prvom prihlásení!
 */
async function seedAdmin() {
  try {
    logger.info('🌱 Creating admin user...');

    const username = 'admin';
    const password = 'admin123';
    const hashedPassword = await hashPassword(password);

    // Check if admin already exists
    const existingAdmins = await db.select().from(users).where(eq(users.username, username));

    if (existingAdmins.length > 0) {
      logger.warn('⚠️  Admin user already exists, skipping...');
      logger.info('\nAdmin credentials:');
      logger.info('  Username: admin');
      logger.info('  Password: (unchanged)');
      return;
    }

    // Create admin user
    const [admin] = await db
      .insert(users)
      .values({
        username,
        password: hashedPassword,
        firstName: 'Admin',
        lastName: 'User',
        role: 'admin',
        changedPassword: true, // Admin už má nastavené heslo
      })
      .returning();

    logger.success('✅ Admin user created successfully!');
    logger.info('\n📋 Admin credentials:');
    logger.info(`  Username: ${username}`);
    logger.info(`  Password: ${password}`);
    logger.warn('\n⚠️  DÔLEŽITÉ: Zmeňte heslo po prvom prihlásení!');

    logger.info('\n📝 Next steps:');
    logger.info('   1. Start the server:');
    logger.info('      npm run dev');
    logger.info('   2. Login as admin');
    logger.info('   3. Create users and add email accounts');

  } catch (error) {
    logger.error('❌ Failed to seed admin user:', error);
    throw error;
  }
}

// Run the script
seedAdmin()
  .then(() => {
    logger.success('🎉 Seed completed!');
    process.exit(0);
  })
  .catch((error) => {
    logger.error('💥 Seed failed:', error);
    process.exit(1);
  });
