const db = require("../db");

exports.createNotification = async (req, res) => {
  try {
    const { title, content, category } = req.body;

    const notification = await db.Notification.create({
      title,
      content,
      category,
    });

    res.status(201).json({
      success: true,
      message: "Notification created successfully",
      data: notification,
    });
  } catch (err) {
    console.error("Error:", err);
    res.status(500).json({
      success: false,
      error: "Failed to create notification",
    });
  }
};

exports.getNotifications = async (req, res) => {
  try {
    const { category } = req.query;
    const where = {};

    if (category && category !== "All") {
      where.category = category;
    }

    const notifications = await db.Notification.findAll({
      where,
      order: [["created_at", "DESC"]],
    });

    res.json({
      success: true,
      data: notifications,
    });
  } catch (err) {
    console.error("Error:", err);
    res.status(500).json({
      success: false,
      error: "Failed to fetch notifications",
    });
  }
};

exports.getNotificationById = async (req, res) => {
  try {
    const notification = await db.Notification.findByPk(req.params.id);
    if (!notification) {
      return res.status(404).json({
        success: false,
        error: "Notification not found",
      });
    }
    res.json({
      success: true,
      data: notification,
    });
  } catch (err) {
    console.error("Error:", err);
    res.status(500).json({
      success: false,
      error: "Failed to fetch notification",
    });
  }
};

exports.updateNotification = async (req, res) => {
  try {
    const notification = await db.Notification.findByPk(req.params.id);
    if (!notification) {
      return res.status(404).json({
        success: false,
        error: "Notification not found",
      });
    }

    await notification.update(req.body);
    res.json({
      success: true,
      message: "Notification updated successfully",
      data: notification,
    });
  } catch (err) {
    console.error("Error:", err);
    res.status(500).json({
      success: false,
      error: "Failed to update notification",
    });
  }
};

exports.deleteNotification = async (req, res) => {
  try {
    const notification = await db.Notification.findByPk(req.params.id);
    if (!notification) {
      return res.status(404).json({
        success: false,
        error: "Notification not found",
      });
    }

    await notification.destroy();
    res.json({
      success: true,
      message: "Notification deleted successfully",
    });
  } catch (err) {
    console.error("Error:", err);
    res.status(500).json({
      success: false,
      error: "Failed to delete notification",
    });
  }
};
