const http = require('http');
const fs = require('fs');
const formidable = require('formidable');

const server = http.createServer((req, res) => {

    // Serve HTML form
    if (req.url === '/upload' && req.method === 'GET') {
        fs.readFile('index.html', (err, data) => {
            if (err) {
                res.writeHead(500);
                return res.end("Error loading file");
            }
            res.writeHead(200, { 'Content-Type': 'text/html' });
            res.end(data);
        });
    }

    // Handle file upload
    else if (req.url === '/upload' && req.method === 'POST') {

        const form = new formidable.IncomingForm();
        form.uploadDir = "./uploads"; // folder to save file
        form.keepExtensions = true;

        form.parse(req, (err, fields, files) => {
            if (err) {
                res.writeHead(500);
                return res.end("Upload Error");
            }

            console.log("File uploaded:", files);

            res.writeHead(200, { 'Content-Type': 'text/plain' });
            res.end("File uploaded successfully 🎉");
        });
    }

    // 404 route
    else {
        res.writeHead(404);
        res.end("404 Not Found");
    }
});

// Start server
const PORT = 3000;
server.listen(PORT, () => {
    console.log(`Server running at http://localhost:${PORT}/upload`);
});