const express = require('express');
const bodyParser = require('body-parser');
const fs = require('fs');
const cors = require('cors');
const path = require('path');

const app = express();
app.use(cors());
app.use(bodyParser.json());
app.use(express.static('public')); // serve article.html

const COMMENTS_FILE = 'comments.json';

function readComments() {
  const data = fs.readFileSync(COMMENTS_FILE, 'utf8');
  return JSON.parse(data);
}

function writeComments(data) {
  fs.writeFileSync(COMMENTS_FILE, JSON.stringify(data, null, 2), 'utf8');
}

// Get comments for a section
app.get('/comments/:section', (req, res) => {
  const section = req.params.section;
  const commentsData = readComments();
  res.json(commentsData[section] || []);
});

// Add a comment
app.post('/comments', (req, res) => {
  const { section, text, comment } = req.body;
  if (!section || !text || !comment) return res.status(400).send('Missing data');

  const commentsData = readComments();

  // Ensure the section exists
  if (!commentsData[section]) {
    commentsData[section] = [];
  }

  const newComment = { id: Date.now(), text, comment }; // unique ID
  commentsData[section].push(newComment);
  writeComments(commentsData);

  res.json(newComment);
});

// Delete a comment
app.delete('/comments/:section/:id', (req, res) => {
  const section = req.params.section;
  const id = parseInt(req.params.id);
  const commentsData = readComments();

  if (!commentsData[section]) {
    return res.sendStatus(404); // no such section
  }

  commentsData[section] = commentsData[section].filter(c => c.id !== id);
  writeComments(commentsData);

  res.sendStatus(200);
});

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