/*
 * @Description: 隐藏/显示审批单
 */
'use strict';
const express = require('express');
const router = express.Router();
const { requireAuthentication } = require("@steedos/auth");
const PermissionManager = require('../manager/permission_manager');
const { getCollection } = require('../utils/collection');

/**
 * 隐藏或显示审批单
 * body {
 *   instance_id: string,
 *   is_hidden: boolean
 * }
 */
router.post('/api/workflow/instance/hide', requireAuthentication, async function (req, res) {
    try {
        const userSession = req.user;
        const userId = userSession.userId;
        const spaceId = userSession.spaceId;
        const { instance_id, is_hidden } = req.body;

        if (!instance_id) {
            throw new Error("instance_id is required");
        }

        const instancesColl = await getCollection('instances');
        const instance = await instancesColl.findOne(
            { _id: instance_id },
            { projection: { state: 1, space: 1, flow: 1, is_hidden: 1 } }
        );

        if (!instance) {
            throw new Error("未找到申请单");
        }

        if (instance.state !== 'completed') {
            throw new Error("只能对已完成的申请单执行此操作");
        }

        // 检查权限：space admin 或 flow admin
        const spacesColl = await getCollection('spaces');
        const space = await spacesColl.findOne(
            { _id: instance.space },
            { projection: { admins: 1 } }
        );

        const isSpaceAdmin = space && space.admins && space.admins.includes(userId);

        let hasFlowAdmin = false;
        if (!isSpaceAdmin) {
            const permissions = await PermissionManager.getFlowPermissions(instance.flow, userId);
            hasFlowAdmin = permissions.includes('admin');
        }

        if (!isSpaceAdmin && !hasFlowAdmin) {
            throw new Error("无权执行此操作");
        }

        const now = new Date();
        const setObj = {
            is_hidden: !!is_hidden,
            modified: now,
            modified_by: userId
        };

        await instancesColl.updateOne(
            { _id: instance_id },
            { $set: setObj }
        );

        // 同步更新 instance_tasks 的 is_hidden
        const instanceTasksColl = await getCollection('instance_tasks');
        await instanceTasksColl.updateMany(
            { instance: instance_id },
            { $set: { is_hidden: !!is_hidden, modified: now, modified_by: userId } }
        );

        res.status(200).json({
            success: true,
            message: is_hidden ? "隐藏审批单成功" : "显示审批单成功"
        });
    } catch (e) {
        console.error('api_workflow_instance_hide error:', e);
        res.status(200).json({
            errors: [{ errorMessage: e.message }]
        });
    }
});

exports.default = router;
