/**
 * 团队管理API路由
 * 作者: 阿瑞
 * 功能: 处理团队的创建和查询
 * 版本: 1.1.0
 */

import { NextRequest, NextResponse } from "next/server";
import { connectSystemDB, RequestWithDB } from "@/lib/db";
import { AuthUtils } from "@/lib/auth";
import DbConfig from "@/lib/db/config";
import { TeamMemberRole } from "@/models/system/types";

/**
 * 扩展解码令牌接口添加workspaceId
 */
interface DecodedTokenWithWorkspace {
  id: number;
  username: string;
  email: string;
  role_type: string;
  workspace_id: number;
  sub: number;
  iat: number;
  exp: number;
}

/**
 * 生成安全的随机密码
 * @param length 密码长度，默认为12
 * @returns 生成的随机密码
 */
function generateSecurePassword(length = 12): string {
  // 定义字符集
  const lowercase = 'abcdefghijklmnopqrstuvwxyz';
  const uppercase = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
  const numbers = '0123456789';
  const special = '!@#$%^&*()_-+=<>?';
  
  const allChars = lowercase + uppercase + numbers + special;
  
  // 确保密码至少包含每种字符各一个
  let password = '';
  password += lowercase.charAt(Math.floor(Math.random() * lowercase.length));
  password += uppercase.charAt(Math.floor(Math.random() * uppercase.length));
  password += numbers.charAt(Math.floor(Math.random() * numbers.length));
  password += special.charAt(Math.floor(Math.random() * special.length));
  
  // 添加剩余的随机字符
  for (let i = 4; i < length; i++) {
    password += allChars.charAt(Math.floor(Math.random() * allChars.length));
  }
  
  // 打乱字符顺序
  return password.split('').sort(() => 0.5 - Math.random()).join('');
}

/**
 * 错误类型定义
 */
interface ApiError extends Error {
  message: string;
  code?: string;
  status?: number;
}

/**
 * GET 处理获取团队列表请求
 */
export async function GET(req: NextRequest) {
  try {
    // 获取查询参数
    const searchParams = req.nextUrl.searchParams;
    const workspaceId = searchParams.get('workspaceId');
    const userId = searchParams.get('userId');
    
    // 验证必要参数
    if (!workspaceId) {
      return NextResponse.json(
        { 
          success: false,
          error: "工作空间ID为必填项" 
        },
        { status: 400 }
      );
    }
    
    // 使用数据库连接中间件处理请求
    const handler = async (dbReq: RequestWithDB) => {
      let query = '';
      let params: (string | number)[] = [];
      
      // 根据不同的查询参数构建SQL
      if (userId) {
        // 查询用户所属的团队
        query = `
          SELECT t.* 
          FROM teams t
          JOIN user_team_relations utr ON t.id = utr.team_id
          WHERE t.workspace_id = ? 
          AND utr.user_id = ?
          AND t.status = 1
          ORDER BY t.created_at DESC
        `;
        params = [workspaceId, userId];
      } else {
        // 查询工作空间内的所有团队
        query = `
          SELECT * 
          FROM teams 
          WHERE workspace_id = ? 
          AND status = 1
          ORDER BY created_at DESC
        `;
        params = [workspaceId];
      }
      
      // 执行查询
      const [rows] = await dbReq.db.query(query, params);
      
      // 转换结果并排除敏感信息
      const teams = JSON.parse(JSON.stringify(rows)).map((team: Record<string, unknown>) => {
        // 排除敏感信息，使用解构赋值忽略db_password
        // eslint-disable-next-line @typescript-eslint/no-unused-vars
        const { db_password, ...safeTeamData } = team;
        return safeTeamData;
      });
      
      // 返回结果
      return NextResponse.json({
        success: true,
        data: teams
      });
    };
    
    // 执行处理函数
    const wrappedHandler = connectSystemDB(handler);
    return await wrappedHandler(req);
    
  } catch (error: unknown) {
    const err = error as ApiError;
    console.error("获取团队列表出错:", err);
    return NextResponse.json(
      { 
        success: false,
        error: err.message || "获取团队列表失败" 
      },
      { status: 500 }
    );
  }
}

/**
 * POST 处理创建团队请求
 */
export async function POST(req: NextRequest) {
  try {
    // 解析请求体，提取备份的用户ID和工作空间ID
    const requestData = await req.json();
    const { teamName, teamCode, userId: backupUserId, workspaceId: backupWorkspaceId } = requestData;
    
    // 验证必要参数
    if (!teamName || !teamCode) {
      return NextResponse.json(
        { 
          success: false,
          error: "团队名称和团队代码为必填项" 
        },
        { status: 400 }
      );
    }
    
    // 从请求头获取访问令牌
    const authHeader = req.headers.get('Authorization');
    let token = '';
    
    if (authHeader && authHeader.startsWith('Bearer ')) {
      token = authHeader.substring(7);
    } else {
      // 尝试从Cookie中获取
      const tokenCookie = req.cookies.get('accessToken');
      if (tokenCookie) {
        token = tokenCookie.value;
      } else {
        // 尝试读取localStorage中的令牌（从请求中）
        const saasStorage = req.cookies.get('saas-user-storage');
        if (saasStorage) {
          try {
            const storageData = JSON.parse(decodeURIComponent(saasStorage.value));
            if (storageData && storageData.state && storageData.state.accessToken) {
              token = storageData.state.accessToken;
            }
          } catch (e) {
            console.error('解析存储的用户数据失败:', e);
          }
        }
      }
    }
    
    // 准备存储用户ID和工作空间ID
    let userId: number | null = null;
    let workspaceId: number | null = null;
    
    // 验证令牌并获取用户信息
    if (!token && !backupUserId && !backupWorkspaceId) {
      return NextResponse.json(
        { 
          success: false,
          error: "用户未登录" 
        },
        { status: 401 }
      );
    }
    
    // 尝试通过令牌获取用户信息
    if (token) {
      try {
        const user = await AuthUtils.verifyToken(token) as DecodedTokenWithWorkspace;
        // 验证用户信息的完整性
        if (user && user.id && user.workspace_id) {
          userId = Number(user.id);
          workspaceId = Number(user.workspace_id);
          
          // 验证数字有效性
          if (isNaN(userId) || isNaN(workspaceId)) {
            console.error('令牌中用户ID或工作空间ID无效:', { userId, workspaceId });
            userId = null;
            workspaceId = null;
          }
        } else {
          console.error('令牌中用户信息不完整:', user);
        }
      } catch (error) {
        console.error('令牌验证失败:', error);
      }
    }
    
    // 如果令牌验证失败，尝试使用备份的用户信息
    if ((!userId || !workspaceId) && backupUserId && backupWorkspaceId) {
      console.log('使用备份的用户信息:', { backupUserId, backupWorkspaceId });
      userId = Number(backupUserId);
      workspaceId = Number(backupWorkspaceId);
      
      // 验证备份数据有效性
      if (isNaN(userId) || isNaN(workspaceId)) {
        console.error('备份用户ID或工作空间ID无效:', { userId, workspaceId });
        return NextResponse.json(
          { 
            success: false,
            error: "用户信息无效，请重新登录" 
          },
          { status: 401 }
        );
      }
    }
    
    // 最终验证用户信息
    if (!userId || !workspaceId) {
      return NextResponse.json(
        { 
          success: false,
          error: "无法验证用户身份，请重新登录" 
        },
        { status: 401 }
      );
    }
    
    // 验证团队代码格式
    if (!/^[a-zA-Z0-9_]{3,20}$/.test(teamCode)) {
      return NextResponse.json(
        { 
          success: false,
          error: "团队代码只能包含字母、数字和下划线，长度在3-20之间" 
        },
        { status: 400 }
      );
    }
    
    // 使用连接数据库的模式
    const handler = async (dbReq: RequestWithDB) => {
      // 检查团队代码是否已存在
      const [teamRows] = await dbReq.db.query(
        `SELECT * FROM teams WHERE team_code = ?`,
        [teamCode]
      );
      
      // 转换为纯JavaScript对象
      const existingTeams = JSON.parse(JSON.stringify(teamRows));
      
      if (existingTeams.length > 0) {
        return NextResponse.json(
          { 
            success: false,
            error: "该团队代码已存在，请使用其他代码" 
          },
          { status: 409 }
        );
      }
      
      // 为团队生成数据库名称和用户名
      const teamDbName = `team_${teamCode}`;
      const teamUsername = `user_${teamCode}`;
      
      // 生成安全的随机密码
      const teamDbPassword = generateSecurePassword(12);
      
      console.log('准备创建团队，用户ID:', userId, '工作空间ID:', workspaceId);
      console.log('团队数据库信息:', {
        db_name: teamDbName,
        db_username: teamUsername,
        // 不输出密码
      });
      
      // 准备团队创建参数
      const teamParams = {
        team_code: teamCode,
        name: teamName,
        db_host: DbConfig.host,
        db_name: teamDbName,
        db_username: teamUsername,
        db_password: teamDbPassword,
        workspace_id: workspaceId,
        owner_id: userId
      };
      
      console.log('创建团队参数:', {
        ...teamParams,
        db_password: '******' // 不输出密码
      });
      
      // 创建团队
      const [result] = await dbReq.db.query(
        `INSERT INTO teams (
          team_code, name, db_host, db_name, db_username, db_password, 
          workspace_id, owner_id, status, created_at
        ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, 1, NOW())`,
        [
          teamParams.team_code,
          teamParams.name,
          teamParams.db_host,
          teamParams.db_name,
          teamParams.db_username,
          teamParams.db_password,
          teamParams.workspace_id,
          teamParams.owner_id
        ]
      );
      
      // 正确处理插入结果
      const insertResult = JSON.parse(JSON.stringify(result));
      const teamId = insertResult.insertId;
      console.log('团队创建成功，ID:', teamId);
      
      // 建立用户与团队的关系
      await dbReq.db.query(
        `INSERT INTO user_team_relations (
          user_id, team_id, role, created_at
        ) VALUES (?, ?, ?, NOW())`,
        [userId, teamId, TeamMemberRole.OWNER]
      );
      console.log('用户团队关系创建成功');
      
      // 返回成功响应
      return NextResponse.json({
        success: true,
        team: {
          id: teamId,
          team_code: teamCode,
          name: teamName
        }
      }, { status: 201 });
    };
    
    // 执行处理函数
    const wrappedHandler = connectSystemDB(handler);
    return await wrappedHandler(req);
    
  } catch (error: unknown) {
    const err = error as ApiError;
    console.error("创建团队出错:", err);
    return NextResponse.json(
      { 
        success: false,
        error: err.message || "创建团队失败" 
      },
      { status: 500 }
    );
  }
} 