const express = require('express');
const PublishService = require('../services/publish');
const wrapAsync = require('../helpers').wrapAsync;
const { checkCrudPermissions } = require('../middlewares/check-permissions');

const router = express.Router();

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

const publishHandler = wrapAsync(async (req, res) => {
  const { projectId, title, description } = req.body;
  const result = await PublishService.publishToProduction(
    projectId,
    req.currentUser,
    title,
    description,
  );
  res.status(200).send(result);
});

router.post('/', publishHandler);
router.post('/publish', publishHandler);

/**
 * @swagger
 * /api/publish/save-to-stage:
 *   post:
 *     security:
 *       - bearerAuth: []
 *     tags: [Publish]
 *     summary: Save dev content to stage
 *     description: Copies all dev environment content (pages, elements, transitions, audio) to stage environment
 *     requestBody:
 *       required: true
 *       content:
 *         application/json:
 *           schema:
 *             type: object
 *             required:
 *               - projectId
 *             properties:
 *               projectId:
 *                 type: string
 *                 format: uuid
 *     responses:
 *       200:
 *         description: Successfully saved to stage
 *       400:
 *         description: Invalid request or publish already in progress
 */
router.post(
  '/save-to-stage',
  wrapAsync(async (req, res) => {
    const { projectId } = req.body;
    const result = await PublishService.saveToStage(projectId, req.currentUser);
    res.status(200).json(result);
  }),
);

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

module.exports = router;
