'use strict';
const express = require("express");
const router = express.Router();
const { requireAuthentication } = require("@steedos/auth");
const _ = require('lodash');
const { getCollection } = require("../utils/collection");

router.get('/api/workflow/instances/redirect/:insId', requireAuthentication, async function (req, res) {
    const db = {
        instances: await getCollection('instances'),
        instance_tasks: await getCollection('instance_tasks')
    }
    let userSession = req.user;
    const spaceId = userSession.spaceId;
    const userId = userSession.userId;
    const insId = req.params.insId;
    
    const tasks = await db.instance_tasks.find({
        instance: insId,
        is_finished: false,
        handler: userId,
        space: spaceId
    }, {_id: 1}).toArray();

    let redirectUrl = '';
    if(tasks.length > 0){
        redirectUrl = `/app/approve_workflow/instance_tasks/view/${tasks[0]._id}?side_object=instance_tasks&side_listview_id=inbox`
    }else{
        const ins = await db.instances.findOne({_id: insId}, {submitter: 1, outbox_users: 1, state: 1});
        if(ins.submitter === userId){
            redirectUrl = `/app/approve_workflow/instances/view/${insId}?side_object=instance_tasks&side_listview_id=${ins.state === 'completed' ? 'completed' : 'pending'}`
        }else{
            redirectUrl = `/app/approve_workflow/instances/view/${insId}?side_object=instance_tasks&side_listview_id=outbox`
        }
    }

    return res.redirect(redirectUrl);
});
exports.default = router;