const Prayer = require("../models/Prayer");

// Get all prayer requests
const getPrayers = async (req, res) => {
  try {
    const prayers = await Prayer.findAll();
    res.json(prayers);
  } catch (error) {
    console.error("❌ Error fetching prayers:", error); // Add this
    res.status(500).json({ error: "Failed to fetch prayer requests" });
  }
};

// Create a new prayer request
const createPrayers = async (req, res) => {
  try {
    const { memberName, description, requestStatus } = req.body;
    const newRequest = await Prayer.create({
      memberName,
      description,
      requestStatus,
    });
    res.status(201).json(newRequest);
  } catch (error) {
    res.status(500).json({ error: "Failed to create prayer request" });
  }
};

// Update a prayer request
const updatePrayers = async (req, res) => {
  try {
    const { id } = req.params;
    const { requestStatus } = req.body;

    const request = await Prayer.findByPk(id);
    if (!request)
      return res.status(404).json({ error: "Prayer request not found" });

    await request.update({ requestStatus });
    res.json({ message: "Prayer request updated", request });
  } catch (error) {
    res.status(500).json({ error: "Failed to update prayer request" });
  }
};

// Delete a prayer request
const deletePrayers = async (req, res) => {
  try {
    const { id } = req.params;
    const request = await Prayer.findByPk(id);
    if (!request)
      return res.status(404).json({ error: "Prayer request not found" });

    await request.destroy();
    res.json({ message: "Prayer request deleted" });
  } catch (error) {
    res.status(500).json({ error: "Failed to delete prayer request" });
  }
};

module.exports = { getPrayers, createPrayers, updatePrayers, deletePrayers };
