const { resSukses, resError } = require("../../payload/payload.js");

const {
    allOrderItems,
    byIdOrderItem,
    createOrderItem,
    updateOrderItem,
    deleteOrderItem
} = require("./service.js");

const semuaOrderItems = async (req, res) => {
    try {
        const data = await allOrderItems();
        return resSukses(res, 200, "success", "Data order items", data);
    } catch (error) {
        return resError(res, 500, "error", error.message);
    }
};

const orderItemId = async (req, res) => {
    try {
        const { id } = req.params;

        const data = await byIdOrderItem(id);

        if (!data) {
            return resError(res, 404, "error", "Order item tidak ditemukan", null);
        }

        return resSukses(res, 200, "success", "Detail order item", data);
    } catch (error) {
        return resError(res, 500, "error", error.message);
    }
};

const buatOrderItem = async (req, res) => {
    try {
        const { order_id, food_id, quantity, harga } = req.body;

        const body = {
            order_id,
            food_id,
            quantity,
            harga
        };

        const result = await createOrderItem(body);

        return resSukses(res, 201, "success", "Order item berhasil ditambahkan", result);
    } catch (error) {
        return resError(res, 500, "error", error.message);
    }
};

const editOrderItem = async (req, res) => {
    try {
        const { id } = req.params;
        const { order_id, food_id, quantity, harga } = req.body;

        const data = await byIdOrderItem(id);

        if (!data) {
            return resError(res, 404, "error", "Order item tidak ditemukan", null);
        }

        const body = {
            order_id,
            food_id,
            quantity,
            harga
        };

        const result = await updateOrderItem(id, body);

        return resSukses(res, 200, "success", "Order item berhasil diupdate", result);
    } catch (error) {
        return resError(res, 500, "error", error.message);
    }
};

const hapusOrderItem = async (req, res) => {
    try {
        const { id } = req.params;

        const data = await byIdOrderItem(id);

        if (!data) {
            return resError(res, 404, "error", "Order item tidak ditemukan", null);
        }

        await deleteOrderItem(id);

        return resSukses(res, 200, "success", "Order item berhasil dihapus", null);
    } catch (error) {
        return resError(res, 500, "error", error.message);
    }
};

module.exports = {
    semuaOrderItems,
    orderItemId,
    buatOrderItem,
    editOrderItem,
    hapusOrderItem
};
