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

dotenv.config();

/**
 * Seed script pre vytvorenie admin účtu
 */
async function seedAdmin() {
  try {
    logger.info('Starting admin user seed...');

    // Skontroluj či admin už existuje
    const [existingAdmin] = await db
      .select()
      .from(users)
      .where(eq(users.username, 'admin'))
      .limit(1);

    if (existingAdmin) {
      logger.warn('Admin user already exists. Skipping seed.');
      process.exit(0);
    }

    // Vygeneruj temporary password
    const tempPassword = generateTempPassword(16);

    // Hash temporary password
    const hashedTempPassword = await hashPassword(tempPassword);

    // Vytvor admin usera
    const [newAdmin] = await db
      .insert(users)
      .values({
        username: 'admin',
        tempPassword: hashedTempPassword,
        role: 'admin',
        changedPassword: false,
        firstName: 'System',
        lastName: 'Administrator',
      })
      .returning();

    logger.success('Admin user created successfully!');
    logger.info('═══════════════════════════════════════════════════════');
    logger.info('  ADMIN CREDENTIALS');
    logger.info('═══════════════════════════════════════════════════════');
    logger.info(`  Username:          admin`);
    logger.info(`  Temporary Password: ${tempPassword}`);
    logger.info(`  User ID:           ${newAdmin.id}`);
    logger.info('═══════════════════════════════════════════════════════');
    logger.warn('  ⚠️  IMPORTANT: Save this password securely!');
    logger.warn('  ⚠️  You will need to change it after first login.');
    logger.info('═══════════════════════════════════════════════════════');

    process.exit(0);
  } catch (error) {
    logger.error('Failed to seed admin user', error);
    process.exit(1);
  }
}

seedAdmin();
