// server2.js
const express = require('express');
const fs = require('fs');
const path = require('path');
const bodyParser = require('body-parser');

const app = express();
const PORT = 3001;
const DATA_FILE = path.join(__dirname, 'editorContent.json');

// Middleware
app.use(bodyParser.json());
app.use(express.static(path.join(__dirname, 'public'))); // serve your HTML & assets

// GET content
app.get('/editor-content', (req, res) => {
  fs.readFile(DATA_FILE, 'utf8', (err, data) => {
    if (err) {
      if (err.code === 'ENOENT') {
        // File does not exist yet
        return res.json({ content: '' });
      }
      return res.status(500).json({ error: 'Failed to read content' });
    }
    try {
      const json = JSON.parse(data);
      res.json({ content: json.content || '' });
    } catch {
      res.json({ content: '' });
    }
  });
});

// POST content
app.post('/editor-content', (req, res) => {
  const { content } = req.body;
  fs.writeFile(DATA_FILE, JSON.stringify({ content }), err => {
    if (err) return res.status(500).json({ error: 'Failed to save content' });
    res.json({ message: 'Content saved successfully!' });
  });
});

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