/**
 * Server Restart Script
 * Utility script untuk restart server dengan proper cleanup
 */

const { spawn } = require('child_process');
const path = require('path');
const fs = require('fs');

const APP_PATH = path.join(__dirname, '../app.js');
const LOG_DIR = path.join(__dirname, '../logs');

// Ensure log directory exists
if (!fs.existsSync(LOG_DIR)) {
	fs.mkdirSync(LOG_DIR, { recursive: true });
}

const logFile = path.join(LOG_DIR, 'restart-script.log');

function log(message) {
	const timestamp = new Date().toISOString();
	const logMessage = `[${timestamp}] ${message}\n`;
	console.log(message);
	
	try {
		fs.appendFileSync(logFile, logMessage, 'utf8');
	} catch (err) {
		console.error('Error writing to log file:', err);
	}
}

function restartServer() {
	log('========================================');
	log('Starting server restart...');
	log(`App path: ${APP_PATH}`);
	log(`Node version: ${process.version}`);
	log('========================================');
	
	try {
		const child = spawn('node', [APP_PATH], {
			detached: true,
			stdio: ['ignore', 'inherit', 'inherit'],
			env: process.env,
		});
		
		child.unref();
		
		log(`Server restarted with PID: ${child.pid}`);
		log('Server process detached, parent can exit');
		
		// Give child process time to start
		setTimeout(() => {
			log('Restart script completed');
			process.exit(0);
		}, 2000);
		
	} catch (err) {
		log(`Error restarting server: ${err.message}`);
		log(`Stack: ${err.stack}`);
		process.exit(1);
	}
}

// Handle script termination
process.on('SIGINT', () => {
	log('Restart script interrupted');
	process.exit(0);
});

process.on('SIGTERM', () => {
	log('Restart script terminated');
	process.exit(0);
});

// Start restart
restartServer();
