const Database = require('better-sqlite3');
const bcryptjs = require('bcryptjs');
const CryptoJS = require('crypto-js');
const crypto = require('crypto');
const path = require('path');

const FIELD_ENCRYPTION_KEY = process.env.FIELD_ENCRYPTION_KEY || 'dev_field_key_change_in_production_32chars_min!';

function encrypt(text) {
  if (!text) return null;
  try {
    return CryptoJS.AES.encrypt(text, FIELD_ENCRYPTION_KEY).toString();
  } catch (error) {
    console.error('Encryption error:', error);
    return text;
  }
}

function hashEmail(email) {
  if (!email) return null;
  return crypto.createHash('sha256').update(email.toLowerCase()).digest('hex');
}

async function createTestUser() {
  const dbPath = path.join(__dirname, 'skillmate.dev.db');
  console.log(`Opening database at: ${dbPath}`);
  const db = new Database(dbPath);

  try {
    console.log('\n=== Creating Test User ===\n');
    
    const email = 'test.user@example.com';
    const hashedPassword = await bcryptjs.hash('test123', 10);
    const encryptedEmail = encrypt(email);
    const emailHash = hashEmail(email);
    const userId = 'user-' + Date.now();
    
    db.prepare(`
      INSERT INTO users (id, username, email, email_hash, password, role, is_active, created_at, updated_at)
      VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
    `).run(
      userId,
      'test.user',
      encryptedEmail,
      emailHash,
      hashedPassword,
      'user',
      1,
      new Date().toISOString(),
      new Date().toISOString()
    );
    
    console.log('✓ Test user created successfully!');
    console.log('Email:', email);
    console.log('Username: test.user');
    console.log('Password: test123');
    console.log('Role: user');
    
    // Show all users
    const users = db.prepare('SELECT id, username, role, is_active FROM users').all();
    console.log('\nAll users in database:');
    users.forEach(user => console.log(' -', user));
    
  } catch (error) {
    console.error('Error creating test user:', error);
    process.exit(1);
  } finally {
    db.close();
  }
}

createTestUser();
