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

export class UserController {
  static async createUser(req: Request, res: Response) {
    try {
      const { name, phone, password } = req.body;
      
      if (!name || !phone) {
        return res.status(400).json({
          success: false,
          message: '姓名和手机号不能为空'
        });
      }
      
      const errors = UserModel.validateUserData({ name, phone, password });
      if (errors.length > 0) {
        return res.status(400).json({
          success: false,
          message: '数据验证失败',
          errors
        });
      }
      
      const user = await UserModel.create({ name, phone, password });
      
      // 自动加入"全体用户"组
      const allUsersGroup = await UserGroupModel.getSystemGroup();
      if (allUsersGroup) {
        await UserGroupModel.addMember(allUsersGroup.id, user.id);
      }

      res.json({
        success: true,
        data: user
      });
    } catch (error: any) {
      console.error('创建用户失败:', error);
      
      // 处理手机号唯一约束错误
      if (error.code === 'SQLITE_CONSTRAINT' || error.message.includes('手机号已存在')) {
        return res.status(400).json({
          success: false,
          message: '该手机号已被注册，请使用其他手机号'
        });
      }
      
      res.status(500).json({
        success: false,
        message: error.message || '创建用户失败'
      });
    }
  }

  static async getUser(req: Request, res: Response) {
    try {
      const { id } = req.params;
      
      const user = await UserModel.findById(id);
      if (!user) {
        return res.status(404).json({
          success: false,
          message: '用户不存在'
        });
      }
      
      res.json({
        success: true,
        data: user
      });
    } catch (error: any) {
      console.error('获取用户信息失败:', error);
      res.status(500).json({
        success: false,
        message: error.message || '获取用户信息失败'
      });
    }
  }

  static async validateUserInfo(req: Request, res: Response) {
    try {
      const { name, phone, password } = req.body;
      
      if (!name || !phone) {
        return res.status(400).json({
          success: false,
          message: '姓名和手机号不能为空'
        });
      }
      
      const errors = UserModel.validateUserData({ name, phone, password });
      if (errors.length > 0) {
        return res.status(400).json({
          success: false,
          message: '数据验证失败',
          errors
        });
      }
      
      const existingUser = await UserModel.findByPhone(phone);
      
        if (existingUser) { 
        if (existingUser.password && existingUser.password !== password) {
          return res.status(400).json({
            success: false,
            message: '密码错误'
          });
        }
        
        if (!existingUser.password && password) {
          await UserModel.updatePasswordById(existingUser.id, password);
        }
        
        res.json({
          success: true,
          data: existingUser
        });
      } else {
        const newUser = await UserModel.create({ name, phone, password });
          // 自动加入"全体用户"组
          const allUsersGroup = await UserGroupModel.getSystemGroup();
          if (allUsersGroup) {
            await UserGroupModel.addMember(allUsersGroup.id, newUser.id);
          }
        res.json({
          success: true,
          data: newUser
        });
      }
    } catch (error: any) {
      console.error('验证用户信息失败:', error);
      res.status(500).json({
        success: false,
        message: error.message || '验证用户信息失败'
      });
    }
  }

  static async getUsersByName(req: Request, res: Response) {
    try {
      const { name } = req.params;
      
      if (!name || typeof name !== 'string') {
        return res.status(400).json({
          success: false,
          message: '姓名不能为空'
        });
      }
      
      const users = await UserModel.findByName(name);
      
      res.json({
        success: true,
        data: users
      });
    } catch (error: any) {
      console.error('根据姓名查询用户失败:', error);
      res.status(500).json({
        success: false,
        message: error.message || '根据姓名查询用户失败'
      });
    }
  }
}