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

const {
    allFood,
    byIdFood,
    createFood,
    updateFood,
    deleteFood
} = require("./service.js");


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

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

        const data = await byIdFood(id);

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

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


const buatFood = async (req, res) => {
    try {
        const { nama_makanan, harga, deskripsi, category_id } = req.body;

        const foto = req.file
            ? `${req.protocol}://${req.get("host")}/uploads/${req.file.filename}`
            : null;

        const body = {
            nama_makanan,
            harga,
            deskripsi,
            category_id,
            foto
        };

        const result = await createFood(body);

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


const editFood = async (req, res) => {
    try {
        const { id } = req.params;
        const { nama_makanan, harga, deskripsi, category_id } = req.body;

        const data = await byIdFood(id);

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

        const foto = req.file
            ? `${req.protocol}://${req.get("host")}/uploads/${req.file.filename}`
            : data.foto;

        const body = {
            nama_makanan,
            harga,
            deskripsi,
            category_id,
            foto
        };

        const result = await updateFood(id, body);

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


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

        const data = await byIdFood(id);

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

        await deleteFood(id);

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

module.exports = {
    semuaFood,
    foodId,
    buatFood,
    editFood,
    hapusFood
};