const { Op } = require('sequelize');
const { Events } = require('../../models');
const { formatCase, formatImage } = require('../../util/formatter');

exports.getEvents = async (req, res, next) => {
  try {
    const { type } = req.query;
    const now = new Date();

    let where = {
      active: true,
    };
    let order = [['createdAt', 'DESC']];

    if (type === 'upcoming') {
      const threeDaysLater = new Date(now.getTime() + 3 * 24 * 60 * 60 * 1000);
      where = {
        active: true,
        start_date: {
          [Op.gte]: now,
          [Op.lte]: threeDaysLater,
        },
      };
      order = [['start_date', 'ASC']];
    } else {
      order = [['createdAt', 'DESC']];
    }

    let events = await Events.findAll({
      where,
      attributes: { exclude: ['active'] },
      order,
    });

    events = events.map((item) => {
      const event = item.get({ plain: true });
      event.image = event.image ? formatImage(event.image, 'events') : null;
      return event;
    });

    return res.status(200).json({
      success: true,
      data: formatCase(events),
    });
  } catch (error) {
    next(error);
  }
};

exports.getEvent = async (req, res, next) => {
  try {
    const { id } = req.params;

    let event = await Events.findOne({
      where: {
        id,
        active: true,
      },
      attributes: { exclude: ['active'] },
    });

    event = event.get({ plain: true });
    event.image = event.image ? formatImage(event.image, 'events') : null;

    return res.status(200).json({
      success: true,
      data: formatCase(event),
    });
  } catch (error) {
    next(error);
  }
};
