import { Request, Response } from 'express';
import { UserGroupModel } from '../models/userGroup';

export const userGroupController = {
  // 获取所有用户组
  getAll: async (req: Request, res: Response) => {
    try {
      const groups = await UserGroupModel.findAll();
      res.json(groups);
    } catch (error: any) {
      res.status(500).json({ error: error.message });
    }
  },

  // 创建用户组
  create: async (req: Request, res: Response) => {
    try {
      const { name, description } = req.body;
      if (!name) {
        return res.status(400).json({ error: '用户组名称不能为空' });
      }
      
      const group = await UserGroupModel.create({ name, description });
      res.status(201).json(group);
    } catch (error: any) {
      res.status(400).json({ error: error.message });
    }
  },

  // 更新用户组
  update: async (req: Request, res: Response) => {
    try {
      const { id } = req.params;
      const { name, description } = req.body;
      
      const group = await UserGroupModel.update(id, { name, description });
      res.json(group);
    } catch (error: any) {
      res.status(400).json({ error: error.message });
    }
  },

  // 删除用户组
  delete: async (req: Request, res: Response) => {
    try {
      const { id } = req.params;
      await UserGroupModel.delete(id);
      res.json({ message: '用户组删除成功' });
    } catch (error: any) {
      res.status(400).json({ error: error.message });
    }
  },

  // 获取用户组成员
  getMembers: async (req: Request, res: Response) => {
    try {
      const { id } = req.params;
      const members = await UserGroupModel.getMembers(id);
      res.json(members);
    } catch (error: any) {
      res.status(500).json({ error: error.message });
    }
  }
};
