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

dotenv.config();

/**
 * Seed script pre vytvorenie test usera
 */
async function seedTestUser() {
  try {
    logger.info('Starting test user seed...');

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

    if (existingUser) {
      logger.warn('Test user already exists. Deleting old one...');
      await db.delete(users).where(eq(users.username, 'testuser'));
    }

    const tempPassword = 'testuser123!';
    const hashedTempPassword = await hashPassword(tempPassword);

    // Vytvor test usera
    const [newUser] = await db
      .insert(users)
      .values({
        username: 'testuser',
        tempPassword: hashedTempPassword,
        role: 'member',
        changedPassword: false,
        firstName: 'Test',
        lastName: 'User',
      })
      .returning();

    logger.success('Test user created successfully!');
    logger.info('═══════════════════════════════════════════════════════');
    logger.info('  TEST USER CREDENTIALS');
    logger.info('═══════════════════════════════════════════════════════');
    logger.info(`  Username:          testuser`);
    logger.info(`  Temporary Password: ${tempPassword}`);
    logger.info(`  User ID:           ${newUser.id}`);
    logger.info(`  Role:              ${newUser.role}`);
    logger.info('═══════════════════════════════════════════════════════');

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

seedTestUser();
