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 { Catalog } = require('../models/catalog');

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

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 catalogs = await Catalog.findAllIdApp(idapp);
  let orders = null;

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

router.get('/id/:id', async function (req, res) {
  const id = req.params.id;

  try {
    var catalog = await Catalog.getCatalogById(id);

    if (catalog) {
      return res.send({ code: server_constants.RIS_CODE_OK, catalog: catalog });
    } else {
      return res.send({ code: server_constants.RIS_CODE_OK, catalog: null });
    }
  } catch (e) {
    console.error('Error fetching catalog by ID:', e);
    return res.status(400).send({ code: server_constants.RIS_CODE_ERR, msg: e.message });
  }
});


router.post('/addnew', authenticate, async function (req, res, next) {
  const idapp = req.body.idapp;
  const data = req.body.newCatalog;
  const username = req.user.username;

  try {
    const newrecs = await globalTables.addNewCatalog(idapp, data, username);
    if (newrecs) {      
      return res.send({ code: server_constants.RIS_CODE_OK, data: newrecs });
    } else {
      return res.send({ code: server_constants.RIS_CODE_OK, data: null });
    }
  } catch (e) {
    console.error('Error fetching catalog by ID:', e);
    return res.status(400).send({ code: server_constants.RIS_CODE_ERR, msg: e.message });
  }
});

module.exports = router;
