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/form/:formId/version/:versionId', requireAuthentication, async function (req, res) {
    try {
        const { formId, versionId } = req.params;
        const formsColl = await getCollection('forms');

        const form = await formsColl.aggregate([
        {
            $match: {
            "_id": formId
            }
        },
        {
            $project: {
            name: 1,
            current_no: 1,
            versionData: {
                $cond: {
                if: { $eq: ["$current._id", versionId] },
                then: "$current",
                else: {
                    $arrayElemAt: [
                    {
                        $filter: {
                        input: "$historys",
                        as: "history",
                        cond: { $eq: ["$$history._id", versionId] }
                        }
                    },
                    0
                    ]
                }
                }
            }
            }
        },
        {
            $match: {
            "versionData": { $ne: null }
            }
        },
        { $limit: 1 } // 限制只返回一个文档
        ]).next();

        if (form) {
        res.status(200).send(form.versionData);
        } else {
        res.status(404).send({ message: "流程版本未找到" });
        }
    } catch (error) {
        console.error('Unexpected error:', error);
        res.status(500).send({
            error: error.message
        });
    }
});
exports.default = router;