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

router.post('/api/workflow/flow/:flowId/settings/update_distribute_settings', requireAuthentication, async function (req, res) {
    try {
        let userSession = req.user;
        const spaceId = userSession.spaceId;
        const userId = userSession.userId;
        const isSpaceAdmin = userSession.is_space_admin;

        if(!isSpaceAdmin){
            throw new Error('no permission!')
        }

        const flowsCollection = await getCollection('flows');
        const usersCollections = await getCollection('users');

        const {
            distribute_optional_users_id = [],
            distribute_to_self,
            distribute_end_notification,
            upload_after_being_distributed
        } = req.body;

        const step_flows = [];

        const bKeys = _.keys(req.body)
        _.each(bKeys, (k)=>{
            const v = req.body[k];
            if(k.startsWith('step_distribute_flows_')){
                step_flows.push({
                    _id: _.last(k.split('step_distribute_flows_')),
                    distribute_optional_flows: v
                })
            }
        })

        const flow_id = req.params.flowId;

        // Find the flow
        const flow = await flowsCollection.findOne({ _id: flow_id });
        if (!flow) {
            return res.status(404).json({ error: 'Flow not found' });
        }

        // Prepare update object
        const setObj = {};

        // Update step flows if needed
        if (flow.current && flow.current.steps) {
            const updatedSteps = flow.current.steps.map(s => {
                if (s.allowDistribute === true) {
                    const matchingStep = step_flows.find(sf => sf._id === s._id);
                    if (matchingStep) {
                        return {
                            ...s,
                            distribute_optional_flows: matchingStep.distribute_optional_flows
                        };
                    }
                }
                return s;
            });

            if (!_.isEmpty(step_flows)) {
                setObj['current.steps'] = updatedSteps;
            }
        }

        // Get optional users
        const distribute_optional_users = await usersCollections.find({
            _id: { $in: distribute_optional_users_id }
        }, {
            projection: { name: 1 }
        }).map(u => ({
            id: u._id,
            name: u.name
        })).toArray();

        setObj.distribute_optional_users = distribute_optional_users;
        setObj.distribute_optional_users_id = distribute_optional_users_id;
        setObj.distribute_to_self = distribute_to_self;
        setObj.distribute_end_notification = distribute_end_notification;
        setObj.upload_after_being_distributed = upload_after_being_distributed;

        // Update the flow
        await flowsCollection.updateOne(
            { _id: flow_id },
            { $set: setObj }
        );

        return res.status(200).send({
            "status": 0,
            "msg": null,
            "data": {}
        });

    } catch (error) {
        console.log(error)
        res.status(200).send({
            "status": 500,
            "msg": error.message
        });
    }
})


exports.default = router;