/**
 * 团队数据模型
 * 作者: 阿瑞
 * 功能: 提供团队相关的数据访问方法
 * 版本: 1.2
 */

import { NextResponse, NextRequest } from 'next/server';
import { connectSystemDB, RequestWithDB } from '@/lib/db';
import { DefaultRoleType } from '@/models/system/types/IUserRole';
import { ITeamBasicInfo, ITeam } from '@/models/system/types';

/**
 * 模拟请求对象类型
 */
interface MockRequest {
  headers: {
    get: (name: string) => string | null;
  };
  json: () => Promise<Record<string, unknown>>;
}

/**
 * API响应类型
 */
interface ApiResponse {
  success: boolean;
  data?: unknown;
  error?: string;
}

/**
 * 团队模型
 * 提供团队相关数据操作函数
 */
export class TeamModel {
  /**
   * 创建模拟请求对象
   */
  private static createMockRequest(): MockRequest {
    return {
      headers: { get: () => null },
      json: async () => ({})
    };
  }

  /**
   * 获取工作空间内的团队列表
   * @param workspaceId 工作空间ID
   * @param userId 用户ID，可选，提供时将根据用户权限筛选
   * @param userRoleType 用户角色类型，可选
   * @returns 团队列表
   */
  static async getTeamsByWorkspace(
    workspaceId: number | string,
    userId?: number | null,
    userRoleType?: DefaultRoleType
  ): Promise<ITeamBasicInfo[]> {
    try {
      const handler = async (req: RequestWithDB) => {
        let rows;
        
        // 如果是管理员用户，获取整个工作空间的团队
        if (userRoleType === DefaultRoleType.ADMIN && userId) {
          [rows] = await req.db.query(
            `SELECT t.id, t.team_code as teamCode, t.name, t.status
             FROM teams t 
             WHERE t.workspace_id = ?
             ORDER BY t.name ASC`,
            [workspaceId]
          );
        } else if (userId) {
          // 如果是普通用户，只获取用户关联的团队
          [rows] = await req.db.query(
            `SELECT t.id, t.team_code as teamCode, t.name, t.status
             FROM teams t
             JOIN user_team_relations utr ON t.id = utr.team_id
             WHERE t.workspace_id = ? AND utr.user_id = ?
             ORDER BY t.name ASC`,
            [workspaceId, userId]
          );
        } else {
          // 无用户身份时，获取所有团队
          [rows] = await req.db.query(
            `SELECT t.id, t.team_code as teamCode, t.name, t.status
             FROM teams t 
             WHERE t.workspace_id = ?
             ORDER BY t.name ASC`,
            [workspaceId]
          );
        }
        
        // 转换为普通JavaScript对象
        const teamRows = JSON.parse(JSON.stringify(rows));
        
        return NextResponse.json({
          success: true,
          data: teamRows
        });
      };
      
      const wrappedHandler = connectSystemDB(handler);
      
      // 执行处理函数，模拟请求
      const mockReq = this.createMockRequest();
      
      const response = await wrappedHandler(mockReq as unknown as NextRequest);
      const data = await response.json() as ApiResponse;
      
      // 从响应中提取团队数据
      return data.success && data.data ? data.data as ITeamBasicInfo[] : [];
    } catch (error) {
      console.error('获取团队列表失败:', error);
      return [];
    }
  }

  /**
   * 根据团队代码获取团队信息
   * @param teamCode 团队代码
   * @returns 团队信息对象或null
   */
  static async getByTeamCode(teamCode: string): Promise<ITeam | null> {
    try {
      const handler = async (req: RequestWithDB) => {
        const [rows] = await req.db.query(
          `SELECT * FROM teams WHERE team_code = ?`,
          [teamCode]
        );
        
        // 转换为纯JavaScript对象
        const teams = JSON.parse(JSON.stringify(rows));
        
        return NextResponse.json({
          success: true,
          data: teams.length > 0 ? teams[0] : null
        });
      };
      
      const wrappedHandler = connectSystemDB(handler);
      
      // 执行处理函数，模拟请求
      const mockReq = this.createMockRequest();
      
      const response = await wrappedHandler(mockReq as unknown as NextRequest);
      const data = await response.json() as ApiResponse;
      
      // 从响应中提取团队数据
      return data.success && data.data ? data.data as ITeam : null;
    } catch (error) {
      console.error(`获取团队(代码: ${teamCode})失败:`, error);
      return null;
    }
  }
} 