const fs = require('fs');
const path = require('path');
const mysql = require('mysql2/promise');
require('dotenv').config();

async function setupDatabase() {
  const config = {
    host: process.env.DB_HOST || 'localhost',
    user: process.env.DB_USER || 'root',
    password: process.env.DB_PASSWORD || '',
    multipleStatements: true,
  };

  console.log('Connecting to MySQL...');
  const connection = await mysql.createConnection(config);

  const sqlPath = path.join(__dirname, '../../database.sql');
  const sql = fs.readFileSync(sqlPath, 'utf8');

  console.log('Creating SMS database and tables...');
  await connection.query(sql);
  await connection.end();

  console.log('MySQL database SMS is ready.');
}

setupDatabase().catch((error) => {
  console.error('MySQL setup failed:', error.message);
  console.error('\nMake sure MySQL is running and check backend-project/.env:');
  console.error('  DB_HOST=localhost');
  console.error('  DB_USER=root');
  console.error('  DB_PASSWORD=your_mysql_password');
  console.error('  DB_NAME=SMS');
  process.exit(1);
});
