import News from '../models/news.js';

// GET /api/news
export const getAll = async (req, res) => {
  try {
    const data = await News.getAll();
    res.json(data);
  } catch (err) {
    res.status(500).json({ message: err.message });
  }
};

// GET /api/news/:slug
export const getOne = async (req, res) => {
  try {
    const data = await News.getBySlug(req.params.slug);
    if (!data) return res.status(404).json({ message: 'News post not found.' });
    res.json(data);
  } catch (err) {
    res.status(500).json({ message: err.message });
  }
};

// POST /api/news
export const create = async (req, res) => {
  try {
    const body = req.body;
    if (body.content && typeof body.content === 'string') {
      body.content = JSON.parse(body.content);
    }
    if (req.file) body.image = `public/uploads/${req.file.filename}`;
    await News.create(body);
    res.status(201).json({ message: 'News post created.' });
  } catch (err) {
    res.status(500).json({ message: err.message });
  }
};

// PUT /api/news/:id
export const update = async (req, res) => {
  try {
    const body = req.body;
    if (body.content && typeof body.content === 'string') {
      body.content = JSON.parse(body.content);
    }
    if (req.file) body.image = `public/uploads/${req.file.filename}`;
    const affected = await News.update(req.params.id, body);
    if (!affected) return res.status(404).json({ message: 'News post not found.' });
    res.json({ message: 'News post updated.' });
  } catch (err) {
    res.status(500).json({ message: err.message });
  }
};

// DELETE /api/news/:id
export const remove = async (req, res) => {
  try {
    const affected = await News.remove(req.params.id);
    if (!affected) return res.status(404).json({ message: 'News post not found.' });
    res.json({ message: 'News post deleted.' });
  } catch (err) {
    res.status(500).json({ message: err.message });
  }
};