/**
 * 邀请令牌验证API路由
 * 作者: 阿瑞
 * 功能: 验证邀请令牌的有效性并返回相关信息
 * 版本: 1.3
 */

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

/**
 * 验证邀请令牌
 */
export async function GET(request: NextRequest) {
  try {
    // 获取令牌参数
    const { searchParams } = new URL(request.url);
    const token = searchParams.get('token');
    
    // 验证参数
    if (!token) {
      return NextResponse.json(
        { 
          success: false,
          error: '缺少令牌参数' 
        },
        { status: 400 }
      );
    }
    
    console.log('验证邀请令牌:', token);
    
    // 使用连接数据库的模式
    const handler = async (req: RequestWithDB) => {
      // 先查询是否是已使用的令牌
      const [usedRows] = await req.db.query(
        `SELECT i.id, u.username, i.used_at
         FROM workspace_invitations i
         LEFT JOIN system_users u ON i.used_by = u.id
         WHERE i.token = ? AND i.used_by IS NOT NULL`,
        [token]
      );
      
      // 转换为纯JavaScript对象
      const usedInvitations = JSON.parse(JSON.stringify(usedRows));
      
      // 如果令牌已被使用，返回更明确的信息
      if (usedInvitations && usedInvitations.length > 0) {
        const usedInvitation = usedInvitations[0];
        console.log('邀请令牌已被使用:', usedInvitation);
        
        return NextResponse.json(
          { 
            success: false,
            error: '该邀请链接已被使用',
            used: true,
            usedBy: usedInvitation.username || '其他用户',
            usedAt: usedInvitation.used_at
          },
          { status: 400 }
        );
      }
      
      // 查询令牌
      const [rows] = await req.db.query(
        `SELECT i.*, w.name as workspace_name, u.username as inviter_name 
         FROM workspace_invitations i
         JOIN workspaces w ON i.workspace_id = w.id
         JOIN system_users u ON i.created_by = u.id
         WHERE i.token = ? AND i.used_by IS NULL AND i.expires_at > NOW()`,
        [token]
      );
      
      // 转换为纯JavaScript对象
      const invitations = JSON.parse(JSON.stringify(rows));
      
      // 打印查询结果，用于调试
      console.log('邀请记录查询结果:', JSON.stringify(invitations && invitations.length > 0 ? invitations[0] : {}, null, 2));
      
      // 如果未找到有效令牌
      if (!invitations || invitations.length === 0) {
        console.log('未找到有效的邀请令牌');
        return NextResponse.json(
          { 
            success: false,
            error: '无效的邀请令牌或已过期' 
          },
          { status: 404 }
        );
      }
      
      const invitation = invitations[0];
      console.log('找到有效的邀请令牌:', invitation.id);
      
      // 检查是否有新的角色字段
      const hasNewRoleFields = invitation.hasOwnProperty('role_type') && 
                               invitation.hasOwnProperty('role_name') && 
                               invitation.hasOwnProperty('is_custom_role');
      
      // 确保字段名称统一
      const responseData = {
        success: true,
        valid: true,
        workspaceId: invitation.workspace_id,
        workspaceName: invitation.workspace_name,
        inviterId: invitation.created_by,
        inviterName: invitation.inviter_name,
        role: invitation.role,
        // 新角色系统字段
        role_type: hasNewRoleFields ? invitation.role_type : invitation.role,
        role_name: hasNewRoleFields ? invitation.role_name : (invitation.role === 'admin' ? '管理员' : '普通用户'),
        is_custom_role: hasNewRoleFields ? invitation.is_custom_role : false,
        expiresAt: invitation.expires_at,
        // 增加额外的字段格式，保证前端能够正确读取
        workspace_id: invitation.workspace_id,
        workspace_name: invitation.workspace_name,
        created_by: invitation.created_by,
        inviter_name: invitation.inviter_name
      };
      
      console.log('响应数据:', responseData);
      
      // 返回邀请相关信息
      return NextResponse.json(responseData);
    };
    
    // 执行处理函数
    const wrappedHandler = connectSystemDB(handler);
    return await wrappedHandler(request);
    
  } catch (error: unknown) {
    console.error('验证邀请令牌失败:', error);
    
    return NextResponse.json(
      { 
        success: false,
        error: '验证邀请令牌失败: ' + (error instanceof Error ? error.message : String(error))
      },
      { status: 500 }
    );
  }
} 