/*
 * @Author: baozhoutao@steedos.com
 * @Date: 2022-09-15 13:09:51
 * @LastEditors: liaodaxue
 * @LastEditTime: 2023-12-26 17:40:35
 * @Description: 
 */
const express = require("express");
const router = express.Router();
const { requireAuthentication } = require("@steedos/auth");
const _ = require('lodash');
const { getCollection } = require('../utils/collection'); // Assuming collection.js is in the same directory
const UUFlowManager = require('../manager/uuflow_manager');
router.post('/api/workflow/v2/draft', requireAuthentication, async function (req, res) {
    try {
        const userSession = req.user;
        const { instance = {} } = req.body;
        
        if (!instance.space) {
            instance.space = userSession.spaceId;
        }

        try {
            // Assuming UUFlowManager.create_instance is an async function
            // If it's not, you'll need to promisify it or refactor it to be async
            const new_ins_id = await UUFlowManager.create_instance(
                instance, 
                Object.assign({}, userSession, { _id: userSession.userId })
            );

            const instancesCollection = await getCollection('instances');
            const new_ins = await instancesCollection.findOne({
                _id: new_ins_id
            }, {
                projection: {
                    space: 1,
                    flow: 1,
                    flow_version: 1,
                    form: 1,
                    form_version: 1
                }
            });

            res.status(200).send({
                instance: new_ins
            });
        } catch (error) {
            console.error('Error creating instance:', error);
            res.status(500).send({
                error: error.message
            });
        }
    } catch (error) {
        console.error('Unexpected error:', error);
        res.status(500).send({
            error: error.message
        });
    }
});
exports.default = router;