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

import { NextResponse, NextRequest } from 'next/server';
import { connectSystemDB, RequestWithDB } from '@/lib/db';
import { WorkspaceStatus } from './types';

/**
 * MySQL查询结果行类型
 */
interface MySQLRow {
  [key: string]: string | number | boolean | Date | null;
}

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

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

/**
 * 工作空间接口
 */
export interface IWorkspace {
  id: number;
  name: string;
  status: WorkspaceStatus;
  creator_id: number;
  created_at: Date;
  updated_at?: Date;
}

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

  /**
   * 根据ID查找工作空间
   * @param id 工作空间ID
   * @returns 工作空间对象或null
   */
  static async getById(id: number): Promise<IWorkspace | null> {
    try {
      const handler = async (req: RequestWithDB) => {
        const [rows] = await req.db.query(
          'SELECT * FROM workspaces WHERE id = ?',
          [id]
        );
        
        const workspaces = rows as MySQLRow[];
        return NextResponse.json({
          success: true,
          data: workspaces.length > 0 ? workspaces[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 IWorkspace : null;
    } catch (error) {
      console.error('获取工作空间失败:', error);
      return null;
    }
  }
} 