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

// DYNAMIC DATABASE_URL RESOLVER UNTUK CPANEL
let databaseUrl = "mysql://hmfupimy_dbuser:w6V%25ri%23r%5EmD%3F!)nc@localhost:3306/hmfupimy_hmf?connection_limit=2&pool_timeout=15"; // default TCP localhost
const socketPaths = [
    "/var/lib/mysql/mysql.sock",
    "/tmp/mysql.sock",
    "/var/run/mysqld/mysqld.sock"
];
let workingSocket = null;
for (const socketPath of socketPaths) {
    try {
        if (fs.existsSync(socketPath)) {
            workingSocket = socketPath;
            break;
        }
    } catch (e) {}
}
if (workingSocket) {
    databaseUrl = `mysql://hmfupimy_dbuser:w6V%25ri%23r%5EmD%3F!)nc@localhost/hmfupimy_hmf?socket=${workingSocket}&connection_limit=2&pool_timeout=15`;
    try { fs.writeFileSync('./public/db-resolved.txt', 'Detected socket: ' + workingSocket + '\nResolved URL: ' + databaseUrl); } catch (e) {}
} else {
    // Fallback ke TCP Domain jika tidak ada socket local
    databaseUrl = "mysql://hmfupimy_dbuser:w6V%25ri%23r%5EmD%3F!)nc@hmfupi.or.id:3306/hmfupimy_hmf?connection_limit=2&pool_timeout=15";
    try { fs.writeFileSync('./public/db-resolved.txt', 'No socket detected. Using TCP domain URL: ' + databaseUrl); } catch (e) {}
}

process.env.DATABASE_URL = databaseUrl;
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);
            const { pathname } = parsedUrl;

            // Serve files from public/uploads directly from filesystem
            if (pathname && pathname.startsWith('/uploads/')) {
                const filePath = path.join(__dirname, 'public', pathname);
                if (fs.existsSync(filePath)) {
                    const stat = fs.statSync(filePath);
                    const ext = path.extname(filePath).toLowerCase();
                    let contentType = 'application/octet-stream';
                    if (ext === '.jpg' || ext === '.jpeg') contentType = 'image/jpeg';
                    else if (ext === '.png') contentType = 'image/png';
                    else if (ext === '.gif') contentType = 'image/gif';
                    else if (ext === '.webp') contentType = 'image/webp';
                    else if (ext === '.svg') contentType = 'image/svg+xml';
                    
                    res.writeHead(200, {
                        'Content-Type': contentType,
                        'Content-Length': stat.size
                    });
                    const readStream = fs.createReadStream(filePath);
                    readStream.pipe(res);
                    return;
                }
            }

            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}`);
    });
});
