const express = require('express');
const router = express.Router();

const tools = require('../tools/general');

var server_constants = require('../tools/server_constants');

var { Project } = require('../models/project');

var { authenticate, auth_default } = require('../middleware/authenticate');

const _ = require('lodash');

const Product = require('../models/product');
const Variant = require('../models/variant');

/*const Department = require('../models/Department')
const Category = require('../models/Category')
const TypedError = require('../modules/ErrorHandler')
const paypal_config = require('../configs/paypal-config')
const paypal = require('paypal-rest-sdk')
 */

const CartClass = require('../modules/Cart')
const Cart = require('../models/cart');

//GET /products
router.post('/', auth_default, async function (req, res, next) {
  const idapp = req.body.idapp;

  var products = await Product.findAllIdApp(idapp, "");

  if (products)
    res.send({ code: server_constants.RIS_CODE_OK, products });
  else
    res.status(400).send(e);

  /*
  const { query, order } = tools.categorizeQueryString(req.query)
  Product.getAllProducts(query, order, function (e, products) {
    if (e) {
      e.status = 406; return next(e);
    }
    if (products.length < 1) {
      // return res.status(404).json({ message: "products not found" })
      return [];
    }
    res.json({ products: products })
  })
  */

});

router.post('/:code', auth_default, async function (req, res, next) {
  const idapp = req.body.idapp;
  const code = req.body.code;

  var product = await Product.findAllIdApp(idapp, code);

  if (product.length > 0) {
    return res.send({ code: server_constants.RIS_CODE_OK, product: product[0] });
  }

});

module.exports = router;
