const { createServer } = require('http');
const { parse } = require('url');
const next = require('next');
const fs = require('fs');

// ═══════════════════════════════════════════
// HARDCODE ENV — karena cPanel gak baca .env
// ═══════════════════════════════════════════
process.env.DATABASE_URL = "mysql://hmfupimy_dbuser:w6V%25ri%23r%5EmD%3F!)nc@127.0.0.1:3306/hmfupimy_hmf?connection_limit=3";
process.env.NEXTAUTH_SECRET = "supersecret_hmf_website_token_123";
process.env.AUTH_SECRET = "supersecret_hmf_website_token_123";
process.env.NODE_ENV = "production";

// ═══════════════════════════════════════════
// LOG STARTUP
// ═══════════════════════════════════════════
const startTime = new Date().toISOString();
const logMsg = `[${startTime}] Server.js berhasil dijalankan\nDB URL: ${process.env.DATABASE_URL.replace(/:[^:]+@/, ':****@')}\nNode: ${process.version}`;
fs.writeFileSync('./public/server-log.txt', logMsg);
console.log(logMsg);

// ═══════════════════════════════════════════
// UNCAUGHT ERROR HANDLER — biar gak crash total
// ═══════════════════════════════════════════
process.on('uncaughtException', (err) => {
    const errMsg = `[${new Date().toISOString()}] UNCAUGHT: ${err.message}\n${err.stack}`;
    fs.appendFileSync('./public/server-log.txt', '\n' + errMsg);
    console.error(errMsg);
});

process.on('unhandledRejection', (reason) => {
    const errMsg = `[${new Date().toISOString()}] UNHANDLED REJECTION: ${reason}`;
    fs.appendFileSync('./public/server-log.txt', '\n' + errMsg);
    console.error(errMsg);
});

// ═══════════════════════════════════════════
// GRACEFUL SHUTDOWN — biar proses gak numpuk
// ═══════════════════════════════════════════
let server;
process.on('SIGTERM', () => {
    console.log('SIGTERM received — shutting down...');
    if (server) server.close(() => process.exit(0));
});

// ═══════════════════════════════════════════
// NEXT.JS START
// ═══════════════════════════════════════════
const port = process.env.PORT || 3000;
const app = next({ dev: false });
const handle = app.getRequestHandler();

app.prepare().then(() => {
    server = createServer((req, res) => {
        try {
            const parsedUrl = parse(req.url, true);
            handle(req, res, parsedUrl);
        } catch (err) {
            console.error('Error handling request:', req.url, err.message);
            res.statusCode = 500;
            res.end('internal server error');
        }
    });

    server.listen(port, () => {
        const readyMsg = `> Ready on http://localhost:${port}`;
        console.log(readyMsg);
        fs.appendFileSync('./public/server-log.txt', '\n' + readyMsg);
    });
}).catch((err) => {
    const fatalMsg = `[${new Date().toISOString()}] FATAL: Next.js failed to prepare — ${err.message}`;
    fs.writeFileSync('./public/server-log.txt', '\n' + fatalMsg);
    console.error(fatalMsg);
    process.exit(1);
});
