const express = require('express');
const { requireCapability } = require('../middleware/auth');
const {
  getConnection,
  importWorkersFromPayload,
  saveConnection,
  syncWorkers
} = require('../services/workday');

const router = express.Router();

router.get('/workday/connection', requireCapability('admin.integrations'), (req, res) => {
  res.json({ connection: getConnection() });
});

router.put('/workday/connection', requireCapability('admin.integrations'), (req, res) => {
  res.json({ connection: saveConnection(req.body, req.user.id) });
});

router.post('/workday/sync-workers', requireCapability('admin.integrations'), async (req, res, next) => {
  try {
    res.json(await syncWorkers(req.user.id));
  } catch (error) {
    next(error);
  }
});

router.post('/workday/import-workers', requireCapability('admin.integrations'), (req, res) => {
  res.json(importWorkersFromPayload(req.body.workers || req.body, req.user.id));
});

module.exports = router;
