const {
  getAllOrder,
  getOrderWithUser,
  createOrderService,
  deleteOrder,
} = require("./servis.js");

const ambilSemua = async (req, res) => {
  try {
    const data = await getAllOrder();
    res.status(200).json(data);
  } catch (error) {
    res.status(500).json({ message: error.message });
  }
};

const ambilDetail = async (req, res) => {
  try {
    const data = await getOrderWithUser(req.params.id);
    if (!data)
      return res.status(404).json({ message: "Order tidak ditemukan" });
    res.status(200).json(data);
  } catch (error) {
    res.status(500).json({ message: error.message });
  }
};

const tambahOrder = async (req, res) => {
  try {
    const { total_harga, status, produk_id, jumlah } = req.body;
    const userId = req.user.id;

    const data = await createOrderService({
      user_id: userId,
      produk_id: produk_id,
      jumlah: jumlah,
      total_harga: total_harga,
      status: status || "pending",
      tanggal_pesan: new Date(),
    });

    res.status(201).json({
      message: "Order Berhasil!",
      data,
    });
  } catch (error) {
    res.status(400).json({ message: error.message });
  }
};

const hapusOrder = async (req, res) => {
  try {
    const { id } = req.params;
    const hasil = await deleteOrder(id);
    if (!hasil)
      return res.status(404).json({ message: "Order tidak ditemukan" });
    res.status(200).json({ message: "Order berhasil dihapus" });
  } catch (error) {
    res.status(500).json({ message: error.message });
  }
};

module.exports = { ambilSemua, ambilDetail, tambahOrder, hapusOrder };
