const Announcements = require("../models/Announcements");
const jwt = require("jsonwebtoken");
const errorHandler = require("../util/errorHandler");

// Create a new Announcements
exports.createAnnouncements = async (req, res, next) => {
    try {
        const {
            title,
            description,
            for_user,
            end_date
        } = req.body;

        const currentDateTime = new Date(); // Get the current date and time
  
        Announcements.create({
            title: title,
            description: description,
            for_user: for_user,
            created_at: currentDateTime,
            end_date: end_date
        });
  
        res.status(201).json({ success: "Announcement successfully created!" });
    } catch (err) {
        next(err);
    }
  };

  // Get all Announcements
exports.getAllAnnouncements = async (req, res, next) => {
    try {
      const announcement = await Announcements.findAll();
  
      const announcementsResponse = announcement.map(announcements = ({
            title,
            description,
            for_user,
            created_at,
            end_date
     }) => ({
            title: title,
            description: description,
            for_user: for_user,
            created_at: created_at,
            end_date: end_date
     })
     
      );
      
      res.status(200).json(announcementsResponse);
    } catch (error) {
      next(error)
    }
};

// Get Announcements by Id
exports.getAnnouncementsId = async (req, res, next) => {
    const { AnnouncementsId } = req.params;
  
    try {
      const announcement = await Announcements.findByPk(AnnouncementsId);
  
      if (!announcement) {
        return res.status(404).json({ error: 'Announcements not found' });
      }
  
      res.status(200).json(announcement);
    } catch (error) {
        next(error)
    }
  };

  // Delete Announcements
exports.deleteAnnouncements = async (req, res, next) => {
    const { AnnouncementsId } = req.params;
  
    try {
      const announcement = await Announcements.findByPk(AnnouncementsId);
  
      if (!announcement) {
        return res.status(404).json({ error: 'Announcements not found' });
      }
  
      await announcement.destroy();
  
      res.status(204).send();
    } catch (error) {
      next(error)
    }
  };

  // Update Announcements by ID
exports.updateAnnouncements = async (req, res, next) => {
    const { AnnouncementsId } = req.params;
    try {
      const announcement = await Announcements.findByPk(AnnouncementsId);
  
      if (!announcement) {
        return res.status(404).json({ error: 'announcement not found' });
      }
  
      const { title, description, for_user, created_at, end_date } = req.body;
  
      await announcement.update({
            title,
            description,
            for_user,
            created_at,
            end_date
      });
  
      res.status(200).json(announcement);
    } catch (error) {
      next(error)
    }
  };