/**
 * 单个团队查询API路由
 * 作者: 阿瑞
 * 功能: 根据团队代码查询团队信息
 * 版本: 1.0
 */

import { NextRequest, NextResponse } from "next/server";
import { connectSystemDB, RequestWithDB } from "@/lib/db";

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

/**
 * GET 处理获取单个团队信息请求
 * 符合Next.js 15.3+的路由处理器签名
 */
export async function GET(req: NextRequest) {
  try {
    // 从URL路径中提取团队代码
    const pathname = req.nextUrl.pathname;
    const teamCode = pathname.split('/')[3]; // 路径格式: /api/teams/[teamCode]
    
    // 验证必要参数
    if (!teamCode) {
      return NextResponse.json(
        { 
          success: false,
          error: "团队代码为必填项" 
        },
        { status: 400 }
      );
    }
    
    // 使用数据库连接中间件处理请求
    const handler = async (dbReq: RequestWithDB) => {
      // 执行查询
      const [rows] = await dbReq.db.query(
        `SELECT * FROM teams WHERE team_code = ? AND status = 1`,
        [teamCode]
      );
      
      // 转换结果为JS对象
      const teams = JSON.parse(JSON.stringify(rows));
      
      // 检查是否找到团队
      if (teams.length === 0) {
        return NextResponse.json(
          { 
            success: false,
            error: "未找到指定的团队" 
          },
          { status: 404 }
        );
      }
      
      // 获取第一个结果并排除敏感信息
      const team = teams[0];
      const { ...safeTeamData } = team;
      
      // 查询团队拥有者信息
      const [ownerRows] = await dbReq.db.query(
        `SELECT id, username, email FROM system_users WHERE id = ?`,
        [team.owner_id]
      );
      
      const owners = JSON.parse(JSON.stringify(ownerRows));
      const ownerInfo = owners.length > 0 ? owners[0] : null;
      
      // 查询团队成员数量
      const [memberCountRows] = await dbReq.db.query(
        `SELECT COUNT(*) as member_count FROM user_team_relations WHERE team_id = ?`,
        [team.id]
      );
      
      const memberCounts = JSON.parse(JSON.stringify(memberCountRows));
      const memberCount = memberCounts.length > 0 ? memberCounts[0].member_count : 0;
      
      // 组装完整的团队信息
      const teamWithDetails = {
        ...safeTeamData,
        owner: ownerInfo,
        member_count: memberCount
      };
      
      // 返回结果
      return NextResponse.json({
        success: true,
        data: teamWithDetails
      });
    };
    
    // 执行处理函数
    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 }
    );
  }
} 