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

// POST → Create new cake order
export const createCakeOrder = async (req, res) => {
  try {
    let { name, phone, cemail, email, order, totalPieces, totalPrice, hst } = req.body;

    // ✅ Validation
    if (!name || !phone || !cemail) {
      return res.status(400).json({ message: "Name, phone, and email are required" });
    }

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

    if (!totalPieces || !totalPrice) {
      return res.status(400).json({ message: "Total pieces and price are required" });
    }

    // ✅ Auto-calculate HST if not provided
    if (!hst || hst <= 0) {
      hst = parseFloat((totalPrice * 0.13).toFixed(2));
    }

    // ✅ Create new order
    const newOrder = await CakeOrder.create({
      name,
      phone,
      email,
      cemail,
      order,
      totalPieces,
      totalPrice,
      hst,
    });

    // ✅ Send email (async)
    if (email) {
      sendCakeOrderMail(name, cemail, phone, email, order, totalPieces, totalPrice, hst)
        .then(() => console.log("Cake order email sent to", email))
        .catch((err) => console.error("Email send failed:", err));
    }

    // ✅ Return response
    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 → Fetch all cake 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 });
  }
};
