const mysql = require('mysql2/promise');

async function createDatabase() {
  let connection;
  
  try {
    // Connect to MySQL without specifying a database
    connection = await mysql.createConnection({
      host: 'localhost',
      user: 'root',
      password: '', // Update this if you have a root password
      port: 3306
    });

    console.log('Connected to MariaDB/MySQL server');

    // Create the database if it doesn't exist
    await connection.execute('CREATE DATABASE IF NOT EXISTS smile24');
    console.log('Database "smile24" created or already exists');

    // Create a user for the application (optional)
    try {
      await connection.execute(`CREATE USER IF NOT EXISTS 'smile24user'@'localhost' IDENTIFIED BY 'smile24password'`);
      await connection.execute(`GRANT ALL PRIVILEGES ON smile24.* TO 'smile24user'@'localhost'`);
      await connection.execute('FLUSH PRIVILEGES');
      console.log('User "smile24user" created with privileges');
    } catch (userError) {
      console.log('User creation skipped (may already exist)');
    }

    console.log('Database setup completed successfully!');
    
  } catch (error) {
    console.error('Error setting up database:', error.message);
    
    if (error.code === 'ECONNREFUSED') {
      console.log('\nTroubleshooting:');
      console.log('1. Make sure MariaDB/MySQL is running');
      console.log('2. Check if the service is started:');
      console.log('   - brew services start mariadb');
      console.log('   - or: sudo systemctl start mariadb');
    }
    
    if (error.code === 'ER_ACCESS_DENIED_ERROR') {
      console.log('\nTroubleshooting:');
      console.log('1. Update the password in this script if your root user has a password');
      console.log('2. Or update your .env.local with the correct credentials');
    }
    
  } finally {
    if (connection) {
      await connection.end();
    }
  }
}

createDatabase();
