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

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

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

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

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

const _ = require('lodash');

const { MyScrapingBook } = require('../models/myscrapingbook');
const Product = require('../models/product');

const AmazonBookScraper = require('../modules/Scraping');

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

  try {
    let myscraping = null;
    if (isbn) {
      myscraping = await MyScrapingBook.findOne({ isbn }).lean();

      if (!myscraping && forzacaricamento) {
        const scraper = new AmazonBookScraper();

        const options = {
          update: false,
          forzaricarica: false,
        };

        const myproduct = await Product.getProductByIsbn(idapp, isbn);
        if (myproduct && myproduct.length > 0) {
          myscraping = await scraper.scrapeISBN(myproduct[0], isbn, options);
          // console.log(myscraping);
        }
      }
    }

    if (myscraping) {
      return res.send({ code: server_constants.RIS_CODE_OK, myscraping });
    } else {
      return res.send({ code: server_constants.RIS_CODE_OK, myscraping: null });
    }
  } catch (e) {
    console.error(e);
    return res.status(400).send({ code: server_constants.RIS_CODE_ERR, msg: e.message });
  }
});

module.exports = router;
