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

async function listEvents(req, res) {
  const { limit = '6', page = '1', from, to, sort = 'start' } = /** @type {any} */ (req.query);
  const q = {};
  if (from) q.start = { ...(q.start || {}), $gte: new Date(from) };
  if (to) q.start = { ...(q.start || {}), $lte: new Date(to) };

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

  const [items, total] = await Promise.all([
    EventModel.find(q)
      .sort({ [sort]: 1 })
      .skip(skip)
      .limit(lim)
      .lean(),
    EventModel.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 createEvent(req, res) {
  const data = pick(req.body, ['title', 'start', 'end', 'place', 'teaser', 'cover', 'to']);
  const doc = await EventModel.create(data);
  return res.status(201).json(doc);
}

async function updateEvent(req, res) {
  const data = pick(req.body, ['title', 'start', 'end', 'place', 'teaser', 'cover', 'to']);
  const doc = await EventModel.findByIdAndUpdate(req.params.id, data, { new: true });
  if (!doc) return res.status(404).json({ message: 'Evento non trovato' });
  return res.json(doc);
}

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

module.exports = { listEvents, createEvent, updateEvent, deleteEvent };
