const express = require("express");
const router = express.Router();
const { requireAuthentication } = require("@steedos/auth");
const { getObject } = require('@steedos/objectql')
const _ = require('lodash');

router.delete('/api/workflow/v2/attachment/:instanceId/:id', requireAuthentication, async function (req, res) {
    try {
        const { instanceId, id} = req.params;
        const fileObject = getObject('cfs_instances_filerecord');
        await fileObject.delete(id);

        const files = await fileObject.find({
            filters: [['metadata.parent', '=', instanceId]],
            sort: 'uploadedAt desc', 
            top: 1
        });

        if (files && files.length > 0) {
            const current = files[0];
            const metadata = Object.assign({}, current.metadata || {}, { current: true });
            await fileObject.update(current._id, { metadata });
        }

        res.status(200).send({
            status: 0
        })
    } catch (error) {
        console.error(error);
        res.status(200).send({
            error: error.message
        });
    }
});
exports.default = router;