// message.controller.js

import dotenv from "dotenv";
import axios from "axios";
import Message from "../models/message.model.js";

dotenv.config();

export const sendMessage = async (req, res) => {
  try {
    const { project, name, email, message } = req.body;

    if (!project) return res.status(400).json({ success: false, error: "Project is required" });
    if (!message) return res.status(400).json({ success: false, error: "Message is required" });

    // Save message to MongoDB
    const newMessage = await Message.create({ project, name, email, message });

    // Send WhatsApp Template Message
    const url = `https://graph.facebook.com/v22.0/774121419125441/messages`;
    const payload = {
      messaging_product: "whatsapp",
      to: 917871207631,
      type: "template",
      template: {
        name: "new_message_alert",
        language: { code: "en_US" },
        components: [
          {
            type: "body",
            parameters: [
              { type: "text", text: project || "Project" },
              { type: "text", text: name || "Guest" },
              { type: "text", text: email || "N/A" },
              { type: "text", text: message || "No message" },
            ],
          },
        ],
      },
    };
    const headers = {
      Authorization: `Bearer EAALKxEMPlp0BPkmoTAJlZAZAymtgqzcUuGVdZAZAKSZAw1csXR5Xy2DodBUC2zXckOYvQ2jOV4aFlZAeCo4IuJCyMb5aFt2UfNRQ1pDGk08QlbCjjCTMsZALipZCMNYyNVwN2pTDwUcYeNZByOrweVVdXD1ErZAbzjc04wmR8ilhQXink4it05BatwkZBf3xCLyy3k6R0tgx9JoymQTn83iZANBWDzvmX3vW5dx6Pud6xNEfqYNsjwZDZD`,
      "Content-Type": "application/json",
    };

    const response = await axios.post(url, payload, { headers });
    console.log("✅ WhatsApp API Response:", response.data);

    return res.status(201).json({ success: true, data: newMessage });
  } catch (err) {
    console.error("❌ WhatsApp API Error:", err.response?.data || err.message);
    return res.status(500).json({ success: false, error: "Server Error" });
  }
};

// ✅ Add this function and export it
export const getMessages = async (req, res) => {
  try {
    const { project } = req.query;
    if (!project) return res.status(400).json({ success: false, error: "Project is required" });

    const messages = await Message.find({ project }).sort({ createdAt: -1 });
    return res.status(200).json({ success: true, data: messages });
  } catch (err) {
    console.error(err);
    return res.status(500).json({ success: false, error: "Server Error" });
  }
};
