const mysql = require('mysql2/promise');
const fs = require('fs');
const path = require('path');
const bcrypt = require('bcryptjs');
require('dotenv').config({ path: path.join(__dirname, '../../.env') });

async function initDatabase() {
  const connection = await mysql.createConnection({
    host: process.env.DB_HOST || 'localhost',
    port: process.env.DB_PORT || 3306,
    user: process.env.DB_USER || 'root',
    password: process.env.DB_PASSWORD || '',
    multipleStatements: true,
  });

  try {
    console.log('Creating database and tables...');
    const schema = fs.readFileSync(path.join(__dirname, '../../database/schema.sql'), 'utf8');
    await connection.query(schema);

    // Update admin password with proper bcrypt hash
    const hash = await bcrypt.hash('admin', 10);
    await connection.query('USE peptide_os');
    await connection.query(
      'UPDATE users SET password_hash = ?, role = ?, full_name = ? WHERE username = ?',
      [hash, 'master_admin', 'Administrator', 'admin']
    );

    console.log('Database initialized successfully!');
    console.log('Default login: admin / admin (role: master_admin)');
  } catch (err) {
    console.error('Error initializing database:', err.message);
  } finally {
    await connection.end();
  }
}

initDatabase();
