const Group = require('../models/Group');

// @desc    获取所有群组
// @route   GET /api/groups
// @access  Private/Admin
const getGroups = async (req, res) => {
    try {
        const groups = await Group.findAll();
        res.json(groups);
    } catch (error) {
        res.status(500).json({ message: '服务器错误' });
    }
};

// @desc    获取单个群组
// @route   GET /api/groups/:id
// @access  Private/Admin
const getGroupById = async (req, res) => {
    try {
        const group = await Group.findById(req.params.id);
        if (group) {
            res.json(group);
        } else {
            res.status(404).json({ message: '群组不存在' });
        }
    } catch (error) {
        res.status(500).json({ message: '服务器错误' });
    }
};

// @desc    创建群组
// @route   POST /api/groups
// @access  Private/Admin
const createGroup = async (req, res) => {
    try {
        const { 
            groupId, 
            groupName,
            group_type = 'group',
            creator_id,
            admin_id,
            in_fee_rate = 0,
            in_exchange_rate = 1,
            out_fee_rate = 0,
            out_exchange_rate = 1
        } = req.body;
        
        const groupIdExists = await Group.findByGroupId(groupId);
        
        if (groupIdExists) {
            return res.status(400).json({ message: '群组ID已存在' });
        }

        const id = await Group.create({ 
            group_id: groupId, 
            group_name: groupName,
            group_type,
            creator_id,
            admin_id,
            in_fee_rate,
            in_exchange_rate,
            out_fee_rate,
            out_exchange_rate
        });
        
        const group = await Group.findById(id);
        res.status(201).json(group);
    } catch (error) {
        console.error('创建群组失败:', error);
        res.status(500).json({ message: '服务器错误' });
    }
};

// @desc    更新群组
// @route   PUT /api/groups/:id
// @access  Private/Admin
const updateGroup = async (req, res) => {
    try {
        const { 
            group_name, 
            is_active, 
            in_fee_rate, 
            in_exchange_rate, 
            out_fee_rate, 
            out_exchange_rate 
        } = req.body;
        
        const group = await Group.findById(req.params.id);
        
        if (!group) {
            return res.status(404).json({ message: '群组不存在' });
        }

        await Group.update(req.params.id, { 
            group_name, 
            is_active, 
            in_fee_rate, 
            in_exchange_rate, 
            out_fee_rate, 
            out_exchange_rate 
        });
        
        const updatedGroup = await Group.findById(req.params.id);
        res.json(updatedGroup);
    } catch (error) {
        console.error('更新群组失败:', error);
        res.status(500).json({ message: '服务器错误' });
    }
};

// @desc    删除群组
// @route   DELETE /api/groups/:id
// @access  Private/Admin
const deleteGroup = async (req, res) => {
    try {
        const group = await Group.findById(req.params.id);
        if (!group) {
            return res.status(404).json({ message: '群组不存在' });
        }

        await Group.delete(req.params.id);
        res.json({ message: '群组已删除' });
    } catch (error) {
        res.status(500).json({ message: '服务器错误' });
    }
};

// @desc    添加群组操作人
// @route   POST /api/groups/:groupId/operators
// @access  Private
const addOperator = async (req, res) => {
    try {
        const { groupId } = req.params;
        const { operator_id, operator_username } = req.body;
        const added_by = req.user.id;

        // 检查群组是否存在
        const group = await Group.findByGroupId(groupId);
        if (!group) {
            return res.status(404).json({ message: '群组不存在' });
        }

        // 检查添加人是否是群组创建者或现有操作人
        const isCreator = group.creator_id === added_by;
        const isOperator = await Group.isOperator(groupId, added_by);

        if (!isCreator && !isOperator) {
            return res.status(403).json({ message: '没有权限添加操作人' });
        }

        // 添加操作人
        await Group.addOperator(groupId, {
            operator_id,
            operator_username,
            added_by
        });

        res.status(201).json({ message: '操作人添加成功' });
    } catch (error) {
        console.error('添加操作人失败:', error);
        if (error.message === '该用户已经是操作人') {
            return res.status(400).json({ message: error.message });
        }
        res.status(500).json({ message: '服务器错误' });
    }
};

// @desc    获取群组操作人列表
// @route   GET /api/groups/:groupId/operators
// @access  Private
const getOperators = async (req, res) => {
    try {
        const { groupId } = req.params;
        const operators = await Group.getOperators(groupId);
        res.json(operators);
    } catch (error) {
        console.error('获取操作人列表失败:', error);
        res.status(500).json({ message: '服务器错误' });
    }
};

// @desc    删除群组操作人
// @route   DELETE /api/groups/:groupId/operators/:operatorId
// @access  Private
const removeOperator = async (req, res) => {
    try {
        const { groupId, operatorId } = req.params;
        const userId = req.user.id;

        // 检查群组是否存在
        const group = await Group.findByGroupId(groupId);
        if (!group) {
            return res.status(404).json({ message: '群组不存在' });
        }

        // 检查操作人是否是群组创建者或现有操作人
        const isCreator = group.creator_id === userId;
        const isOperator = await Group.isOperator(groupId, userId);

        if (!isCreator && !isOperator) {
            return res.status(403).json({ message: '没有权限删除操作人' });
        }

        // 删除操作人
        const success = await Group.removeOperator(groupId, operatorId);
        if (!success) {
            return res.status(404).json({ message: '操作人不存在' });
        }

        res.json({ message: '操作人删除成功' });
    } catch (error) {
        console.error('删除操作人失败:', error);
        res.status(500).json({ message: '服务器错误' });
    }
};

module.exports = {
    getGroups,
    getGroupById,
    createGroup,
    updateGroup,
    deleteGroup,
    addOperator,
    getOperators,
    removeOperator
};