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

// HARDCODE SEMUA VARIABEL KARENA CPANEL TIDAK BISA MEMBACA .ENV
process.env.DATABASE_URL = "mysql://hmfupimy_dbuser:w6V%25ri%23r%5EmD%3F!)nc@127.0.0.1:3306/hmfupimy_hmf";
// NEXTAUTH_URL dan AUTH_URL sengaja dihilangkan agar mendukung multi-domain
process.env.NEXTAUTH_SECRET = "supersecret_hmf_website_token_123";
process.env.AUTH_SECRET = "supersecret_hmf_website_token_123";
process.env.NODE_ENV = "production";

fs.writeFileSync('./public/server-log.txt', 'Server.js berhasil dijalankan pada: ' + new Date().toISOString() + '\nDatabase URL: ' + process.env.DATABASE_URL);

// BACA PORT DARI CPANEL
const port = process.env.PORT || 3000;
const dev = false;
const app = next({ dev });
const handle = app.getRequestHandler();

app.prepare().then(() => {
    createServer((req, res) => {
        try {
            const parsedUrl = parse(req.url, true);
            handle(req, res, parsedUrl);
        } catch (err) {
            console.error('Error occurred handling', req.url, err);
            res.statusCode = 500;
            res.end('internal server error');
        }
    }).listen(port, () => {
        console.log(`> Ready on http://localhost:${port}`);
    });
});
