
const express = require('express');
const ProjectsService = require('../services/projects');
const ProjectsDBApi = require('../db/api/projects');
const wrapAsync = require('../helpers').wrapAsync;
const router = express.Router();
const { parse } = require('json2csv');
const { checkCrudPermissions } = require('../middlewares/check-permissions');

// Assuming 'projects' permission exists. If not, I might need to add it to DB or use a generic one.
// For now, I'll use checkCrudPermissions('projects').
// Note: If 'projects' is not in permissions table, this might fail or default to allow/deny depending on implementation.
// Usually we need to add permissions in migration.
// But user didn't ask for granular permissions setup, so I'll assume admin has access or I might need to skip it if it blocks.
// I'll assume 'projects' is the resource name.
// If it fails, I'll remove it.
router.use(checkCrudPermissions('projects'));

/**
 *  @swagger
 *  components:
 *    schemas:
 *      Projects:
 *        type: object
 *        properties:
 *          name:
 *            type: string
 *          description:
 *            type: string
 *          status:
 *            type: string
 *          startDate:
 *            type: string
 *            format: date-time
 *          endDate:
 *            type: string
 *            format: date-time
 */

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

router.put('/:id', wrapAsync(async (req, res) => {
  await ProjectsService.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 ProjectsService.remove(req.params.id, req.currentUser);
  const payload = true;
  res.status(200).send(payload);
}));

router.post('/deleteByIds', wrapAsync(async (req, res) => {
    await ProjectsService.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 ProjectsDBApi.findAll(
    req.query, globalAccess, { currentUser }
  );

  if (filetype && filetype === 'csv') {
    const fields = ['id', 'name', 'description', 'status', 'startDate', 'endDate'];
    const opts = { fields };
    try {
      const csv = parse(payload.rows, opts);
      res.status(200).attachment(csv);
      res.send(csv);
    } catch (err) {
      console.error(err);
      res.status(500).send('Error generating CSV');
    }
  } 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 ProjectsDBApi.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 ProjectsDBApi.findAllAutocomplete(
    req.query.query,
    req.query.limit,
    req.query.offset,
    globalAccess,
    organizationId,
  );
  res.status(200).send(payload);
});

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

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

module.exports = router;
