/*
 * @Author: baozhoutao@steedos.com
 * @Date: 2023-03-10 15:18:11
 * @LastEditors: baozhoutao@steedos.com
 * @LastEditTime: 2023-03-10 15:19:35
 * @Description: 
 */
const express = require("express");
const router = express.Router();
const { requireAuthentication } = require("@steedos/auth");
const { getCollection } = require('../utils/collection');
const _ = require('lodash');

async function getObjectWorkflows(spaceId, userId) {
    // 参数检查
    if (typeof spaceId !== 'string') {
        throw new Error('spaceId must be a string');
    }
    if (typeof userId !== 'string') {
        throw new Error('userId must be a string');
    }

    // 获取space_users集合
    const spaceUsersCollection = await getCollection('space_users');
    const curSpaceUser = await spaceUsersCollection.findOne(
        { space: spaceId, user: userId },
        { projection: { organizations: 1 } }
    );

    if (!curSpaceUser) {
        throw new Error('not-authorized');
    }

    // 获取organizations集合
    const organizationsCollection = await getCollection('organizations');
    const organizations = await organizationsCollection.find({
        _id: {
            $in: curSpaceUser.organizations
        }
    }, { projection: { parents: 1 } }).toArray();

    // 获取object_workflows集合
    const objectWorkflowsCollection = await getCollection('object_workflows');
    let ows = await objectWorkflowsCollection.find(
        { space: spaceId },
        { projection: { object_name: 1, flow_id: 1, space: 1, sync_direction: 1 } }
    ).toArray();

    // 获取flows集合
    const flowsCollection = await getCollection('flows');
    
    // 使用Promise.all并行处理每个工作流
    ows = await Promise.all(ows.map(async (o) => {
        const fl = await flowsCollection.findOne(
            { _id: o.flow_id, state: 'enabled' },
            { projection: { name: 1, perms: 1, forbid_initiate_instance: 1 } }
        );

        if (fl) {
            o.flow_name = fl.name;
            o.can_add = false;
            o.forbid_initiate_instance = fl.forbid_initiate_instance;

            const perms = fl.perms;
            if (perms) {
                if (perms.users_can_add && perms.users_can_add.includes(userId)) {
                    o.can_add = true;
                } else if (perms.orgs_can_add && perms.orgs_can_add.length > 0) {
                    if (curSpaceUser && curSpaceUser.organizations && 
                        _.intersection(curSpaceUser.organizations, perms.orgs_can_add).length > 0) {
                        o.can_add = true;
                    } else if (organizations) {
                        o.can_add = _.some(organizations, (org) => {
                            return org.parents && _.intersection(org.parents, perms.orgs_can_add).length > 0;
                        });
                    }
                }
            }
        }
        return o;
    }));

    // 过滤掉没有flow_name的工作流
    ows = ows.filter(n => n.flow_name);

    return ows;
}


router.get('/api/workflow/v2/get_object_workflows', requireAuthentication, async function (req, res) {
    try {
        let userSession = req.user;
        const { spaceId, userId } = userSession;
        const result = await getObjectWorkflows(spaceId, userId);
        return res.status(200).send(result); 
    } catch (error) {
        console.error(error);
        res.status(200).send({
            error: error.message
        });
    }
});
exports.default = router;