const { body } = require("express-validator");
const {Food, Order} = require("../../db/models/index.js");

const validateCreateOrderItem = [
  body("order_id")
    .notEmpty().withMessage("order_id wajib diisi")
    .isInt().withMessage("order_id harus berupa angka")
    .custom(async (value) => {
      const order = await Order.findByPk(value);
      if (!order) {
        return Promise.reject("order_id tidak ditemukan");
      }
    }),

  body("food_id")
    .notEmpty().withMessage("food_id wajib diisi")
    .isInt().withMessage("food_id harus berupa angka")
    .custom(async (value) => {
      const food = await Food.findByPk(value);
      if (!food) {
        return Promise.reject("food_id tidak ditemukan");
      }
    }),

  body("quantity")
    .notEmpty().withMessage("quantity wajib diisi")
    .isInt({ min: 1 }).withMessage("quantity minimal 1"),

  body("harga")
    .notEmpty().withMessage("harga wajib diisi")
    .isInt({ min: 0 }).withMessage("harga harus berupa angka positif"),
];

const validateUpdateOrderItem = [
  body("order_id")
    .optional()
    .isInt().withMessage("order_id harus berupa angka")
    .custom(async (value) => {
      if (value) {
        const order = await Order.findByPk(value);
        if (!order) {
          return Promise.reject("order_id tidak ditemukan");
        }
      }
    }),

  body("food_id")
    .optional()
    .isInt().withMessage("food_id harus berupa angka")
    .custom(async (value) => {
      if (value) {
        const food = await Food.findByPk(value);
        if (!food) {
          return Promise.reject("food_id tidak ditemukan");
        }
      }
    }),

  body("quantity")
    .optional()
    .isInt({ min: 1 }).withMessage("quantity minimal 1"),

  body("harga")
    .optional()
    .isInt({ min: 0 }).withMessage("harga harus berupa angka positif"),
];

module.exports = {
  validateCreateOrderItem,
  validateUpdateOrderItem
};
