const { execSync } = require('child_process');
const http = require('http');
const path = require('path');

console.log('Starting cPanel DB Migration...');
try {
  // Use backend directory for running command
  const output = execSync('npx prisma migrate deploy', { 
    cwd: __dirname,
    stdio: 'pipe',
    env: { ...process.env }
  });
  console.log('Migration output:', output.toString());
  
  // Start a simple server so cPanel doesn't think the app crashed/failed to start
  http.createServer((req, res) => {
    res.writeHead(200, { 'Content-Type': 'text/plain' });
    res.end('Prisma Migration Completed Successfully!\n\nLog:\n' + output.toString());
  }).listen(process.env.PORT || 5000);
} catch (error) {
  console.error('Migration failed:', error);
  http.createServer((req, res) => {
    res.writeHead(500, { 'Content-Type': 'text/plain' });
    res.end('Prisma Migration Failed!\n\nError:\n' + error.message + '\n\nStack:\n' + error.stack + '\n\nStderr:\n' + (error.stderr ? error.stderr.toString() : ''));
  }).listen(process.env.PORT || 5000);
}
