import { CakeOrder } from "../../models/maisondetreats/cakeOrder.model.js";
import { sendCakeOrderMail } from "../../utils/mailer.js";

export const createCakeOrder = async (req, res) => {
    try {
        const { order, email } = req.body;

        if (!order || typeof order !== "object") {
            return res.status(400).json({ message: "Order data is required" });
        }

        const newOrder = await CakeOrder.create({ order, email });

        // ✅ send confirmation email (non-blocking)
        if (email) {
            sendCakeOrderMail(email, order)
                .then(() => console.log("Cake order email sent to", email))
                .catch((err) => console.error("Email send failed:", err));
        }

        res.status(201).json({
            message: "Cake order created successfully",
            data: newOrder,
        });
    } catch (err) {
        console.error("Error creating cake order:", err);
        res.status(500).json({ message: "Server error", error: err.message });
    }
};
// GET /api/cake-orders → List all orders
export const getAllCakeOrders = async (_req, res) => {
    try {
        const orders = await CakeOrder.find().sort({ createdAt: -1 });
        res.json({ data: orders });
    } catch (err) {
        console.error("Error fetching cake orders:", err);
        res.status(500).json({ message: "Server error", error: err.message });
    }
};
