/*
 * @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 InstanceRecordQueue = require('../../../src/instance_record_queue')
router.get('/api/workflow/v2/forcesync/:insId', requireAuthentication, async function (req, res) {
    try {
        const { insId } = req.params;
        const userSession = req.user;

        if(!userSession.is_space_admin){
            throw new Error('Validate Request -- No permission.')
        }

        const db = {
            object_workflows: await getCollection('object_workflows'),
            instances: await getCollection('instances')
        }
        const ow = await db.object_workflows.findOne({_id: insId});
        const spaceId = ow.space;
        const flowId = ow.flow_id;
        const errorMsgs = [];
        const result = {};

        const records = await db.instances.find({ space: spaceId, flow: flowId, state: { $in: ['pending', 'completed'] }, $or: [{ record_ids: { $exists: false } }, { record_ids: { $size: 0 } }] }, { fields: { name: 1 } }).toArray();
        for (const ins of records) {
            var doc = {
                info: {
                    instance_id: ins._id,
                    records: null
                }
            }
            try {
                await InstanceRecordQueue.sendDoc(doc);
            } catch (error) {
                console.log(error)
                errorMsgs.push({ _id: ins._id, name: ins.name, message: error.message });
            }
        }

        if (errorMsgs.length > 0) {
            result.error = errorMsgs
        }

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