// @ts-check
const { PostModel } = require('../models/Post');
const { pick } = require('../utils/pick');

 async function listPosts(req, res) {
  const { limit = '3', page = '1', sort = '-date', category } = /** @type {any} */ (req.query);
  const q = {};
  if (category) q.category = category;

  const lim = Math.min(Number(limit) || 3, 50);
  const skip = (Math.max(Number(page) || 1, 1) - 1) * lim;

  const [items, total] = await Promise.all([
    PostModel.find(q).sort(sort).skip(skip).limit(lim).lean(),
    PostModel.countDocuments(q)
  ]);

  res.set('Cache-Control', 'public, max-age=30, stale-while-revalidate=120');
  return res.json({ items, total, page: Number(page), limit: lim });
}

 async function createPost(req, res) {
  const data = pick(req.body, ['title','date','category','teaser','cover','to','bodyMd']);
  const doc = await PostModel.create(data);
  return res.status(201).json(doc);
}

 async function updatePost(req, res) {
  const data = pick(req.body, ['title','date','category','teaser','cover','to','bodyMd']);
  const doc = await PostModel.findByIdAndUpdate(req.params.id, data, { new: true });
  if (!doc) return res.status(404).json({ message: 'Post non trovato' });
  return res.json(doc);
}

 async function deletePost(req, res) {
  const r = await PostModel.findByIdAndDelete(req.params.id);
  if (!r) return res.status(404).json({ message: 'Post non trovato' });
  return res.status(204).send();
}

module.exports = { listPosts, createPost, updatePost, deletePost };