const express = require("express");
const router = express.Router();
const authorize = require("../../../../middlewares/authorize-sapps");
const emailGroupService = require("./emailGroup.service");

router.post("/create", authorize(), create);
router.post("/", authorize(), getAll);
router.post("/option", authorize(), option);
router.get("/emails/:id", authorize(), getEmailsForGroup);
router.put("/enabled/:id", authorize(), updateEnabled);
router.put("/:id", authorize(), update);
router.delete("/:id", authorize(), _delete);

module.exports = router;

function create(req, res, next) {
	emailGroupService
		.create(req.body)
		.then((result) => res.json(result))
		.catch(next);
}

function getAll(req, res, next) {
	emailGroupService
		.getAll(req.body)
		.then((result) => res.json(result))
		.catch(next);
}

function option(req, res, next) {
	emailGroupService
		.option(req.body)
		.then((result) => res.json(result))
		.catch(next);
}

function getEmailsForGroup(req, res, next) {
	const companyId = req.query.company_id ? parseInt(req.query.company_id, 10) : undefined;
	emailGroupService
		.getEmailsForGroup(req.params.id, { company_id: companyId })
		.then((result) => res.json(result))
		.catch(next);
}

function updateEnabled(req, res, next) {
	emailGroupService
		.updateEnabled(req.params.id, req.body)
		.then((result) => res.json(result))
		.catch(next);
}

function update(req, res, next) {
	emailGroupService
		.update(req.params.id, req.body)
		.then((result) => res.json(result))
		.catch(next);
}

function _delete(req, res, next) {
	emailGroupService
		.delete(req.params.id)
		.then((result) => res.json(result))
		.catch(next);
}
