const express = require('express');
const { requireCapability } = require('../middleware/auth');
const { publicConfig, saveConfig, syncCmdb, testConnection } = require('../services/servicenow');

const router = express.Router();

router.get('/servicenow/settings', requireCapability('admin.integrations'), (req, res) => {
  res.json({ settings: publicConfig() });
});

router.put('/servicenow/settings', requireCapability('admin.integrations'), (req, res) => {
  res.json({ settings: saveConfig(req.body, req.user.id) });
});

router.post('/servicenow/test', requireCapability('admin.integrations'), async (req, res, next) => {
  try {
    res.json(await testConnection(req.user.id));
  } catch (error) {
    next(error);
  }
});

router.post('/servicenow/cmdb-sync', requireCapability('assets.bulk'), async (req, res, next) => {
  try {
    res.json(await syncCmdb(req.user.id));
  } catch (error) {
    next(error);
  }
});

module.exports = router;
