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');

const { User } = require('../models/user');

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

const _ = require('lodash');

const Product = require('../models/product');
const OrdersCart = require('../models/orderscart');
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;
  const userId = req.body.userId;

  let ismanager = await tools.isManagerByReq(req);

  let products = await Product.findAllIdApp(idapp, "", undefined, ismanager);
  let orders = null;
  if (ismanager) {
    // Prende Tutti gli Ordini !
    orders = await OrdersCart.getOrdersCartByUserId('ALL', idapp, 0, false);
  } else {
    orders = await OrdersCart.getOrdersCartByUserId(userId, idapp, 0, false);
  }

  /*
  let ind = 0;
  for (const ord of orders) {
    let newitems = []
    for (myord of ord.items) {
      if (!myord.order) {
        console.log('NO ORDINE ', myord, 'Ind=', ind);
      } else {
        if (myord.order && !myord.order.hasOwnProperty('idGasordine')) {
          console.log('NO idGasordine', myord);
        } else {
          newitems.push(myord)
        }
      }
    }
    ind++;

    ord.items = newitems
  }
  */

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

});

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] });
  }

});

router.get('/id/:id', async function (req, res) {

  const id = req.params.id;

  var product = await Product.getProductById(id);

  // console.log('Product ID', id, product);

  if (product) {
    return res.send({ code: server_constants.RIS_CODE_OK, product: product });
  } else {
    return res.send({ code: server_constants.RIS_CODE_OK, product: null });
  }

});

module.exports = router;
