const express = require('express')
const router = express.Router()
const db = require('qmi-cloud-common/mongo');
const passport = require('../passport');


/**
 * @swagger
 * /destroyprovisions:
 *    get:
 *      description: Get all DestroyProvision
 *      summary: Get all DestroyProvision
 *      tags:
 *        - admin
 *      produces:
 *        - application/json
 *      responses:
 *        200:
 *          description: JSON Array
 */
router.get('/', passport.ensureAuthenticatedAndAdmin, async (req, res, next) => {

  try {
    const result = await db.destroy.get();
    return res.json(result);
  } catch (error) {
    next(error);
  }
});

/**
 * @swagger
 * /destroyprovisions/{id}:
 *    get:
 *      description: Get DestroyProvision by ID
 *      summary: Get DestroyProvision by ID
 *      tags:
 *        - admin
 *      produces:
 *        - application/json
 *      parameters:
 *        - name: id
 *          in: path
 *          type: string
 *          required: true
 *      responses:
 *        200:
 *          description: DestroyProvision
 *        404:
 *          description: Not found
 *        
 */
router.get('/:id', passport.ensureAuthenticatedAndAdmin, async (req, res, next) => {
  try {
    const mongoJob = await db.destroy.getById(req.params.id);
    if (!mongoJob){
      return res.status(404).json({"msg": "Not found"});
    }
    return res.json(mongoJob);
  } catch (error) {
    next(error);
  }
});

/**
 * @swagger
 * /destroyprovisions/{id}/logs:
 *    get:
 *      description: Get Logs for DestroyProvision by ID
 *      summary: Get Logs for DestroyProvision by ID
 *      produces:
 *        - text/plain
 *      parameters:
 *        - name: id
 *          in: path
 *          type: string
 *          required: true
 *      responses:
 *        200:
 *          description: Log file
 *        404:
 *          description: Not found
 */
router.get('/:id/logs', passport.ensureAuthenticated ,async (req, res, next) => {
  try {
    const mongoJob = await db.destroy.getById(req.params.id);
    if (!mongoJob){
      return res.status(404).json({"msg": "Not found"});
    }
    return res.sendFile(mongoJob.logFile);
  } catch (error) {
    next(error);
  }
});

module.exports = router;