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

const {
    allOrders,
    byIdOrder,
    createOrder,
    updateOrder,
    deleteOrder
} = require("./service.js");

const semuaOrders = async (req, res) => {
    try {
        const data = await allOrders();
        return resSukses(res, 200, "success", "Data orders", data);
    } catch (error) {
        return resError(res, 500, "error", error.message);
    }
};

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

        const data = await byIdOrder(id);

        if (!data) {
            return resError(res, 404, "error", "Maaf, Data order tidak ditemukan", null);
        }

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

const buatOrder = async (req, res) => {
    try {
        const { total_harga, address_id } = req.body;

        const user_id = req.user.id;

        const body = {
            user_id,
            total_harga,
            address_id
        };

        const result = await createOrder(body);

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

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

        const data = await byIdOrder(id);

        if (!data) {
            return resError(res, 404, "error", "Maaf Data order tidak ditemukan", null);
        }

        const body = {
            status
        };

        const result = await updateOrder(id, body);

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

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

        const data = await byIdOrder(id);

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

        await deleteOrder(id);

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

module.exports = {
    semuaOrders,
    orderId,
    buatOrder,
    editOrder,
    hapusOrder
};
