const express = require('express');
const Vat_declarationsService = require('../services/vat_declarations');
const Vat_declarationsDBApi = require('../db/api/vat_declarations');
const wrapAsync = require('../helpers').wrapAsync;
const config = require('../config');
const router = express.Router();
const { parse } = require('json2csv');
const { checkCrudPermissions } = require('../middlewares/check-permissions');

router.use(checkCrudPermissions('vat_declarations'));

router.post('/', wrapAsync(async (req, res) => {
    const referer = req.headers.referer || `${req.protocol}://${req.hostname}${req.originalUrl}`;
    const link = new URL(referer);
    await Vat_declarationsService.create(req.body.data, req.currentUser, true, link.host);
    const payload = true;
    res.status(200).send(payload);
}));

router.post('/bulk-import', wrapAsync(async (req, res) => {
    const referer = req.headers.referer || `${req.protocol}://${req.hostname}${req.originalUrl}`;
    const link = new URL(referer);
    await Vat_declarationsService.bulkImport(req, res, true, link.host);
    const payload = true;
    res.status(200).send(payload);
}));

router.put('/:id', wrapAsync(async (req, res) => {
  await Vat_declarationsService.update(req.body.data, req.body.id, req.currentUser);
  const payload = true;
  res.status(200).send(payload);
}));

router.delete('/:id', wrapAsync(async (req, res) => {
  await Vat_declarationsService.remove(req.params.id, req.currentUser);
  const payload = true;
  res.status(200).send(payload);
}));

router.post('/deleteByIds', wrapAsync(async (req, res) => {
    await Vat_declarationsService.deleteByIds(req.body.data, req.currentUser);
    const payload = true;
    res.status(200).send(payload);
  }));

router.get('/', wrapAsync(async (req, res) => {
  const filetype = req.query.filetype
  const globalAccess = req.currentUser.app_role.globalAccess;
  const currentUser = req.currentUser;
  const payload = await Vat_declarationsDBApi.findAll(
    req.query,  globalAccess,  { currentUser }
  );
  if (filetype && filetype === 'csv') {
    const fields = ['id','notes', 'total_sales_amount','taxable_sales_amount','output_vat_amount','total_purchases_amount','input_vat_amount','vat_payable_amount', 'generated_at','reviewed_at'];
    const opts = { fields };
    try {
      const csv = parse(payload.rows, opts);
      res.status(200).attachment(csv);
      res.send(csv)
    } catch (err) {
      console.error(err);
    }
  } else {
    res.status(200).send(payload);
  }
}));

router.get('/count', wrapAsync(async (req, res) => {
  const globalAccess = req.currentUser.app_role.globalAccess;
    const currentUser = req.currentUser;
    const payload = await Vat_declarationsDBApi.findAll(
        req.query,
         globalAccess, 
        { countOnly: true, currentUser }
    );
    res.status(200).send(payload);
}));

router.get('/autocomplete', async (req, res) => {
  const globalAccess = req.currentUser.app_role.globalAccess;
  const organizationId =  req.currentUser.organization?.id
  const payload = await Vat_declarationsDBApi.findAllAutocomplete(
    req.query.query,
    req.query.limit,
    req.query.offset,
     globalAccess,  organizationId,
  );
  res.status(200).send(payload);
});

router.get('/:id/erca-data', wrapAsync(async (req, res) => {
  const payload = await Vat_declarationsService.getErcaData(
    req.params.id,
    req.currentUser
  );
  res.status(200).send(payload);
}));

router.get('/:id', wrapAsync(async (req, res) => {
  const payload = await Vat_declarationsDBApi.findBy(
    { id: req.params.id },
  );
  res.status(200).send(payload);
}));

router.use('/', require('../helpers').commonErrorHandler);

module.exports = router;