const express = require('express');
const axios = require('axios');
const fs = require('fs');
const path = require('path');

const app = express();
const port = 3000;

// Serve static files (HTML, CSS, JS)
app.use(express.static('public'));

// File upload endpoint
app.post('/upload', async (req, res) => {
  const { fileUrl } = req.body;

  if (!fileUrl) {
    return res.status(400).send('File URL is required.');
  }

  try {
    // Download the file from the URL
    const response = await axios.get(fileUrl, { responseType: 'stream' });

    // Create a unique filename
    const fileName = path.basename(fileUrl);
    const filePath = path.join(__dirname, 'uploads', fileName);

    // Save the file to the "uploads" folder
    const writer = fs.createWriteStream(filePath);
    response.data.pipe(writer);

    writer.on('finish', () => {
      res.send('File uploaded successfully!');
    });

    writer.on('error', (error) => {
      console.error('Error saving file:', error);
      res.status(500).send('Error saving file.');
    });
  } catch (error) {
    console.error('Error downloading file:', error);
    res.status(500).send('Error downloading file.');
  }
});

// Start the server
app.listen(port, () => {
  console.log(`Server is running on http://localhost:${port}`);
});